ajax发起跨域请求
1.jsonp跨域
前端ajax
$.ajax({
type: 'GET',
url: 'http://localhost:80/thinkphp3.2.3/index.php?m=Home&c=Index&a=index',
dataType: "jsonp",
//jsonp: "callback",
//data: {'userid': '25'},
success: function(data) {
alert("success");
},error: function(data){
alert("fail")
}
});
后端php
$data = array(
//'id' => $_GET['userid'],
'msg' => 'Success'
);
echo $_GET['callback'].'('.json_encode($data).')';
2.cors跨域
前端ajax
$.ajax({
type: 'POST',
url: 'http://localhost:80/thinkphp3.2.3/index.php?m=Home&c=Index&a=index',
dataType: "json",
//jsonp: "callback",
data: {'userid': '25'},
success: function(data) {
alert("success");
},error: function(data){
alert("fail")
}
});
后端php记得加入文件头
header('Access-Control-Allow-Origin:*');
$this->ajaxReturn($_POST['userid']);
jsonp只支持get,优势是对老版浏览器的支持
1.jsonp跨域
前端ajax
$.ajax({
type: 'GET',
url: 'http://localhost:80/thinkphp3.2.3/index.php?m=Home&c=Index&a=index',
dataType: "jsonp",
//jsonp: "callback",
//data: {'userid': '25'},
success: function(data) {
alert("success");
},error: function(data){
alert("fail")
}
});
后端php
$data = array(
//'id' => $_GET['userid'],
'msg' => 'Success'
);
echo $_GET['callback'].'('.json_encode($data).')';
2.cors跨域
前端ajax
$.ajax({
type: 'POST',
url: 'http://localhost:80/thinkphp3.2.3/index.php?m=Home&c=Index&a=index',
dataType: "json",
//jsonp: "callback",
data: {'userid': '25'},
success: function(data) {
alert("success");
},error: function(data){
alert("fail")
}
});
后端php记得加入文件头
header('Access-Control-Allow-Origin:*');
$this->ajaxReturn($_POST['userid']);
jsonp只支持get,优势是对老版浏览器的支持
cors支持所有http请求,劣势是部分老版浏览器不支持