问题描述
我尝试确定ajax是否发送了对PHP文件的请求.
我用它搜索了一下,并阅读了很多建议采用以下方法的文章:
I googled it and read a whole a bunch of articles that suggest following method:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo 'This is an ajax request!';
exit;
}
echo 'This is not an ajax request!';
但是我的服务器没有此变量:未定义索引:HTTP_X_REQUESTED_WITH ...
But my server doesn't have this variable: Undefined index: HTTP_X_REQUESTED_WITH ...
这就是我发出ajax请求的方式:
Thats how I make the ajax request:
$.ajax({
url: 'http://URL/test.php',
complete: function(res) {
console.log(res.responseText);
}
});
我正在从其他网址拨打电话,因此我设置了 header('Access-Control-Allow-Origin:*');
I'm making that call from a different url, so I've set header('Access-Control-Allow-Origin: *');
我在 $ _ SERVER
中发现了一个区别:
I have discovered one difference in $_SERVER
though:
Ajax请求: $ _ SERVER [HTTP_ACCEPT] =>*/*
无Ajax请求: $ _ SERVER [HTTP_ACCEPT] =>text/html,application/xhtml + xml,application/xml; q = 0.9,image/webp,*/*; q = 0.8
所以我的问题是,我是否可以将 HTTP_X_REQUESTED_WITH
放入 $ _ SERVER
中?如果不是,是否有适当的方法通过使用 $ _ SERVER [HTTP_ACCEPT]
So my question is, is there a way for me to get HTTP_X_REQUESTED_WITH
into $_SERVER
?And if not, is there a proper way to find out if the request is AJAX by using the $_SERVER[HTTP_ACCEPT]
推荐答案
没有100%的方法来检测请求是否通过ajax发出.即使有人使用"X-Requested-With:XMLHttpRequest"发送标头,您也不应依赖它.
There's no 100% way to detect if the request was made via ajax. Even if someone sends header with "X-Requested-With: XMLHttpRequest" you shouldn't rely on it.
这篇关于如何找出一个请求是否是一个ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!