ajax与yii,ajax 跨域 yii无法检测出是ajax请求

群里面的哥们发现的问题

yii request对象的 isAjax 方法无法正常工作(yii1.x 但猜想yii2 一样的)。

最后说其是使用的跨域调用 。

经验证确实ajax跨域时 没有发送X-Requested-With 头

在stackoverflow 上有这个问题的解决方案:

If you are using jQuery to do your ajax request, it will not send the header X-Requested-With (HTTP_X_REQUESTED_WITH) = XMLHttpRequest, because it is cross domain. But there are 2 ways to fix this and send the header:

Option 1) Manually set the header in the ajax call:

$.ajax({

url: "http://your-url...",

headers: {'X-Requested-With': 'XMLHttpRequest'}

});

Option 2) Tell jQuery not to use cross domain defaults, so it will keep the X-Requested-With header in the ajax request:

$.ajax({

url: "http://your-url...",

crossDomain: false

});

But with this, the server must allow those headers, then the server needs to print those headers:

print "Access-Control-Allow-Origin: *\n";

print "Access-Control-Allow-Headers: X-Requested-With, Content-Type\n";

The first line above will avoid the error "Origin is not allowed by Access-Control-Allow-Origin."

The second line will avoid the error "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers."

php 端跨域改造

这个有好多做法 自行搜索

最简单的先在index.php 中加入:

header('Access-Control-Allow-Origin: *');

也可以用白名单过滤 可以添加多行

本文由 yiqing 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。

可自由转载、引用,但需署名作者且注明文章出处。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值