防跨域--使用jsonp请求后端api
html
思路:
- 引入jquery
设置请求方式为get(jsonp请求只支持get)设置cache为false,禁用缓存- 发起jsonp请求向后端api请求数据
代码:
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jsonp请求实现</title>
</head>
<body>
<div>
<button onclick="request()">点我发送jsonp请求</button>
<p>
api回调响应码: <span id="code"></span>
</p>
<p>
api回调数据:
<div id="data"></div>
</p>
</div>
</body>
</script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script>
function request() {
$.ajax({
url: 'your api url',
dataType: 'jsonp',
cache: false,
success: function (e) {
console.log(e);
$("#code").text(e.code)
const data = JSON.stringify(e.data);
$("#data").text(data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
}
});
}
</script>
</html>
api后端
代码:
使用jsonp助手函数响应(也可使用\think\response\Jsonp真实类响应
不需要设置响应头
点击查看代码
public function index2(){
$page = $this->request->param('page') ?? 0;
$limit = $this->request->param('limit') ?? 10;
$params = $this->request->param();
$res = $this->admins
->withSearch(['id','username','nickname'] , $params)
->order('id','desc')
->paginate($limit,false,[
'page' => $page
]);
$data = [
'code'=>200,
'page' => $res->currentPage(),
'total'=>$res->total(),
'data'=>$res->items(),
];
return jsonp($data);
}

浙公网安备 33010602011771号