get和post时才有这个跨域和cookie跨域的问题,jsonp因为机制不同,无此问题,但是jsonp数据量有限

原生js

1
2
3
// 会带上cookie
var xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials = true;

jquery ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.ajax({
url : rankApi,
dataType : "json",
xhrFields: {
withCredentials: true
},
data:{
},
type : "post",
success : function(res){
},
error : ()=>{
}
})

php相应头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 允许cookie
$header["Access-Control-Allow-Credentials"] = "true";

// 允许跨域
$origin = input("origin", request()->header("Origin"));
if ($origin && in_array($origin, config("alloworigin")))
{
$header["Access-Control-Allow-Origin"] = $origin;
}

// 判断jsonp
if (isset($_GET['callback']))
{
return jsonp($data);
}
else
{
return json($data, 200, $header);
}