代码之家  ›  专栏  ›  技术社区  ›  AskaNor_29

未定义检测AJAX请求$\u服务器['HTTP\u X\u REQUESTED\u WITH']的操作

  •  1
  • AskaNor_29  · 技术社区  · 6 年前

    我正在运行适用于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);
    

    我的发送。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中,我可以看到请求和标题,都在那里,但是如果我将其添加到php代码中的else中,if语句是alwas false

    foreach (getallheaders() as $name => $value) {
    echo "$name: $value\n";}
    

    我可以在firebug的响应中看到,HTTP\u X\u REQUESTED\u WITH仍然存在,因此没有在我的代码中清除,但如果我尝试

    echo $_SERVER['HTTP_X_REQUESTED_WITH'];
    

    我知道这是一个未定义的索引

    我没有对Web服务器进行任何更改,也没有任何更改。htaccess文件,我不明白为什么$\u服务器['HTTP\u X\u REQUESTED\u WITH']不工作。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Quentin    6 年前

    标题名称应为 X-Requested-With

    PHP只是将其转换为所有大写,替换 - 具有 _ 并在其前面加上 HTTP_ 当它以 $_SERVER

    在转换到JS之前,您需要手动进行转换,然后是PHP 再来一次


    X-请求-带 不过,这是一个相当肮脏的黑客行为。我会用一些 Accept: application/json 请求JSON响应而不是HTML响应(并在PHP中查找该标头)。