jsonp实现
客户端
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp测试</title>
</head>
<body id="body">
<script>
function get() {
alert('开始调用');
var theJ = document.createElement('script');
theJ.setAttribute('src', 'http://tp5/index/index/index/?f=jsonP&name=jijuxie');
var body = document.querySelector('#body');
body.appendChild(theJ);
}
setTimeout(function () {
get();
}, 1000);
</script>
</body>
</html>
服务端
这里使用的是tp5框架
tp5/application/index/controller/index.php
<?php
namespace app\index\controller;
use think\Request;
class Index
{
public function index()
{
$request = Request::instance();
$theF = $request->param('f');//读取get参数
$theName = $request->param('name');
if ($request->isGet()&&!empty($theF)) {
$return = ['code' => 0, 'message' => 'jsonp通信成功', 'data' => ['name' => $theName]];
$return = $theF . "(" . json_encode($return) . ")";//拼接字符串成执行方法的样子
} else {
//这个地方可以返回一般json的模式,使这个接口通用jsonp和ajax和一般接口
// $return = ['code' => 0, 'message' => 'ajax/api通信成功', 'data' => ['name' => $theName]];
$return = ['code' => 1, 'message' => '使用了非jsonP', 'data' => []];
}
header('Content-Type: application/json; charset=utf-8');
return $return;
}
}