Ajax发起JSONP跨域请求
我们通过jQuery的JSONP方式可以实现跨域ajax请求,服务端php也需要做出相应的处理,也就是说php这边必须和前端页面按照一定的格式请求和返回数据。
示例:前端页面发起JSONP请求:
$.ajax({
type: "get",
data: "random="+Math.random(),
url: "http://demo.helloweba.net/phpajax/jsonp.php",
dataType: "jsonp",
jsonp: "callback",
success: function(data) {
console.log(data);
},
error: function() {
console.log('Request Error.');
}
});
php后端服务代码可以这样写(注意输出返回的格式):$data = array(
'rand' => $_GET['random'],
'msg' => 'Success'
);
echo $_GET['callback'].'('.json_encode($data).')';