PHP jsonp 实现
PHP服务端代码:
<?php
header('Content-type: application/json');
//获取回调函数名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json数据
$json_data = '["customername1","customername2"]';
//输出jsonp格式的数据
echo $jsoncallback . "(" . $json_data . ")";
?>HTML客户端代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>jsonp</title>
<script src="//cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "get",
async: false,
url: "http://tool.xiaoguan.net/getAddr?jsonp=1&jsoncallback=callbackFunction",
dataType: "jsonp",
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
jsonpCallback:"callbackFunction",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
success: function(json){
console.log('json:',json);
},
error: function(){
console.log('fail:');
}
});
});
</script>
</body>
</html>