1、使用js创建script动态插入页面
1 2 3 4 5 6 7 8 9 10 11
| (function() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://test.com/public/index.php/index/index/index?resume=all&callBack=jsonp'; document.body.firstElementChild.append(script); }())
|
2、创建该方法用来接收后台传过来的数据
1 2 3 4 5
|
function jsonp(response) { console.log(response) }
|
3、服务器端代码
后端接收前端传过来的callBack方法名 然后返回jsonp(data) 执行并把后台查找到的数据放在方法里面
这就是jsonp实现跨越的精髓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?php namespace app\index\controller; use think\Controller; use think\Request; use think\Db;
class Index extends Controller { public function index() { $request = Request::instance(); if($request -> GET()) { $resume = input('resume'); $callBack = input('callBack'); if($resume == 'all') { $data = json_encode(Db::name('resume')->select()); echo $callBack.'('.$data.')'; } } }
|
4、最后前端就可以得到想要的数据了