js+thinkphp 实现jsonp跨越

js+thinkphp 实现jsonp跨越

1、使用js创建script动态插入页面

1
2
3
4
5
6
7
8
9
10
11
// 用来创建script标签
(function() {
// 创建一个script标签
var script = document.createElement('script');
// 指定script的类型
script.type = 'text/javascript';
// 定义script请求的链接 后面加上callBack 请求成功后的回调
script.src = 'http://test.com/public/index.php/index/index/index?resume=all&callBack=jsonp';
// 把创建的标签插入到body的前面
document.body.firstElementChild.append(script);
}())

2、创建该方法用来接收后台传过来的数据

1
2
3
4
5
// (response)参数 用来接收后台传过来的数据
// jsonp 为函数名 可以自定义 但是必须和callBack后面的值一样
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、最后前端就可以得到想要的数据了


images


images

作者

Reself's

发布于

2019-06-14

更新于

2021-02-09

许可协议

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×