如何判断一个请求是否是ajax请求?

2022-01-05 00:00:00 request php ajax

我尝试确定对 PHP 文件的请求是否由 ajax 发送.

我在谷歌上搜索并阅读了一大堆建议使用以下方法的文章:

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);
    }
});

我是从不同的 url 进行调用,所以我设置了 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.

相关文章