简单说一下php解决跨域的问题:
在php脚本中设置响应头:
注:服务器端 Access-Control-Allow-Credentials = true
时,参数Access-Control-Allow-Origin
的值不能为 '*'
。
服务端:test-a.php , 所在域名:http://a.test.com
<?php
// 允许多个域名访问
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = ['http://a.test.com', 'http://b.test.com'];
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
//header('Access-Control-Allow-Origin:*'); // 允许所有域名访问(必选)
header('Access-Control-Allow-Methods:OPTIONS, GET, POST'); // 允许option,get,post请求(可选)
header("Access-Control-Allow-Headers: token, Origin, X-Requested-With, Content-Type, Accept, X-CSRF-Token"); // 允许x-requested-with请求头(可选)
header('Access-Control-Allow-Credentials: true'); // 带 cookie 的跨域访问(可选)
$data = [$_POST, $_COOKIE];
print_r(json_encode($data, JSON_FORCE_OBJECT));
客户端:test-a.html , 所在域名:http://a.test.com
<!DOCTYPE html>
<html>
<head>
<title>Ajax 跨域</title>
</head>
<body>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url: 'http://a.test.com/test-a.php',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
crossDomain:true, //设置跨域为true
xhrFields: {
withCredentials: true //默认情况下,标准的跨域请求是不会发送cookie的
},
success: function (res) {
console.log(res);
console.log('success');
},
error: function (res) {
console.log(res);
console.log('error');
}
});
});
</script>
</html>
客户端:test-b.html , 所在域名:http://b.test.com
<!DOCTYPE html>
<html>
<head>
<title>Ajax 跨域</title>
</head>
<body>
</body>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url: 'http://a.test.com/test-a.php',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
crossDomain:true, //设置跨域为true
xhrFields: {
withCredentials: true //默认情况下,标准的跨域请求是不会发送cookie的
},
success: function (res) {
console.log(res);
console.log('success');
},
error: function (res) {
console.log(res);
console.log('error');
}
});
});
</script>
</html>
执行结果为:
(1)同源访问
(2)不同源访问
从结果分析:同样请求 http://a.test.com/test-a.php ,域名为 b.test.com 可以获取 a.test.com 设置的cookie,但是 a.test.com 却不可以获取 b.test.com 设置的cookie。