我正在为 linux 5.6.33 运行 XAMPP
js代码:
var url = "send.php";
xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.onload = function() {
var decoded_response = JSON.parse(xhttp.responseText);
if (xhttp.readyState == 4 && xhttp.status === 200 && xhttp.responseText && decoded_response) {
//success
}
else if (xhttp.status !== 200 || !xhttp.responseText || !decoded_response) {
//error
}
};
xhttp.send(param);
我的 send.php 文件
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'XMLHttpRequest') {
$encoded = json_encode($ajax_message);
header('Content-Type: application/x-www-form-urlencoded');
echo $encoded;
}
// else just display the message
else {
echo $message;
}
从 firebug 我可以看到请求和 header ,它们都在那里,但是 if 语句总是错误的,如果我将它添加到 php 代码中的 else
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";}
我可以在 Firebug 的响应中看到 HTTP_X_REQUESTED_WITH 仍然存在,所以我的代码中的某处没有被清除,但如果我尝试
echo $_SERVER['HTTP_X_REQUESTED_WITH'];
我知道这是一个 undefined index
我没有对网络服务器进行任何更改,也没有任何 .htaccess 文件,我不明白为什么 $_SERVER['HTTP_X_REQUESTED_WITH'] 不工作。
最佳答案
header 名称应为 X-Requested-With
。
PHP 只是将其全部大写,将 -
替换为 _
并在 $ 中表示时加上前缀
。HTTP_
_服务器
您在它到达您的 JS 之前手动执行该转换,然后 PHP 再次执行。
X-Requested-With
是相当肮脏的 hack。我会使用类似于 Accept: application/json
的内容来请求 JSON 响应而不是 HTML 响应(并在 PHP 中查找该 header )。
关于javascript - 检测 AJAX 请求 $_SERVER ['HTTP_X_REQUESTED_WITH' ] 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299274/