PHP与Ajax跨域

简单说一下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。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值