客户端JS
var xhrurl = 'http://localhost:8001/ajax/index.php';
$.ajax({
type: "get",
async: false,
url: xhrurl,
cache: false,
dataType: "jsonp",
jsonp: "callbackparam",
jsonpCallback: "success_jsonpCallback",
success: function(json) {
alert(json[0].name);
},
error: function(e) {
alert("error");
}
});
服务器
<?php
$str = $_GET['callbackparam'];
$data = [
'status' => 1,
'msg' => 'ok'
];
echo $str . '(' . json_encode($data) . ')';
PS:客户端中的jsonp
参数值是作为jsonpCallback
参数值的键值,通过url来传递jsonCallback
参数值到服务器,例如:
http://localhost:8001/ajax/index.php?callbackparam=success_jsonpCallback
,服务器必须接收到此jsonCallback值后,将需要返回的json用与此值拼接,后返回给客户端,不然客户端会发出警告:
Resource interpreted as Script but transferred with MIME type text/plain:
却看不到success定义的函数执行。