群里面的哥们发现的问题
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."
原始问题地址cross-domain-ajax-doesnt-send-x-requested-with-header
这个有好多做法 自行搜索
最简单的先在index.php 中加入:
header('Access-Control-Allow-Origin: *');
也可以用白名单过滤 可以添加多行
本文由 yiqing 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。