Ajax跨域问题解决

Ajax跨域问题解决(PHP语言)


一:使用jsonp格式, 如jquery中ajax请求参数 dataType:’JSONP’。


<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.ajax({
    url:url,
    type:'GET',
    dataType:'JSONP',
    success: function(data){
        console.log(data);
    }
});
</script>

二,server端通过设置Access-Control-Allow-Origin来实现跨域

例如:客户端的域名是client.example.com,而请求的域名是server.example.com。

如果直接使用ajax访问,会有以下错误:
XMLHttpRequest cannot load http://server.example.com/server.php. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.Origin ‘http://client.example.com’ is therefore not allowed access.

1、允许单个域名访问
指定某域名(http://client.example.com)跨域访问,则只需在http://server.example.com/server.php文件头部添加如下代码:

header('Access-Control-Allow-Origin:http://client.example.com');

2、允许多个域名访问
指定多个域名(http://client1.example.comhttp://client2.example.com等)跨域访问,则只需在http://server.example.com/server.php文件头部添加如下代码:

$origin = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';  

$allow_origin = array(  
    'http://client1.example.com',
    'http://client2.example.com'
);  

if(in_array($origin, $allow_origin)){
    header('Access-Control-Allow-Origin:'.$origin);     
} 

3、允许所有域名访问
允许所有域名访问则只需在http://server.example.com/server.php文件头部添加如下代码:

header('Access-Control-Allow-Origin:*'); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值