【问题标题】:AJAX postdata working on localhost but not on (Apache) serverAJAX postdata 在本地主机上工作但不在(Apache)服务器上
【发布时间】:2017-09-29 16:49:03
【问题描述】:

我发现未通过服务器上的 AJAX 发送 postdata 的问题。为了调试它,我编写了以下相当简约的 javascript 片段来测试一个简单的 AJAX 调用:

function my_custom_ajax(target_page, target_element , postdata_contents) {

  // Sending the XMLHttpRequest as postdata
  var xhr = new XMLHttpRequest();
  xhr.open("POST", target_page, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
  xhr.setRequestHeader("Content-length", postdata_contents.length);
  xhr.setRequestHeader("Connection", "close");
  xhr.send(postdata_contents);

  // Waiting for the request to return
  xhr.onreadystatechange = return_data;

  // If all went well, we update the target element
  function return_data()
  {
    if(xhr.readyState === 4)
    {
      if(xhr.status === 200)
      {
        // We update the target element
        document.getElementById(target_element).innerHTML = xhr.responseText;
      }
      // Throw error in case of 404 or such
      else
        document.getElementById(target_element).innerHTML = "XHR can't be loaded";
    }
    // Throw error in case request got interrupted or didn't work out
    else
      document.getElementById(target_element).innerHTML = "XHR error";
  }
}

使用以下 HTML 调用它:

<div onClick="my_custom_ajax('test_page.php?xhr','my_id','postdata_test');">
  Click me
</div>
<div id="my_id">
  xhr response will appear here
</div>

并调用一个仅包含以下内容的 PHP 页面:

exit(var_dump($_POST));

在我的 Apache localhost 或我拥有的另一台 Apache 服务器中运行这段代码时,它确实将 postdata_contents 中的任何内容作为 postdata 传递。退出(var_dump($_POST));确实表明它工作正常,并打印了我传递给它的 postdata 的值。

但是,当在 Apache 服务器上运行同一段代码时,它不起作用,我得到的只是 «array(0) { } »,因为没有根据 PHP 文件传递​​任何 postdata。

这是 Firefox 的请求详细信息的开发工具视图(法语,抱歉,但应该很明显是什么):

调试工具显示 postdata 内容正在正确发送:

但是,返回的内容显示 postdata 不知何故未通过:

在我的 localhost 和我的其他 Apache 服务器上,一切都完全相同直到最后一步,postdata 被正确传递(var_dump 消息的样式,但你可以很容易地看到它:postdata_test 是 $_POST 的一部分):

经过数小时摆弄此 Apache 服务器的配置并尝试了我能想到的所有调试方法和断点后,我的神经过于紧张,现在无法继续理性地思考这个问题。由于我没有选择使用另一台服务器或只是将我的本地 Apache 配置文件复制粘贴到新服务器上,所以我把这个问题留给大家,希望有人能弄清楚或曾经遇到过类似的事情。

提前致谢, 埃里克 B.

【问题讨论】:

    标签: ajax apache post xmlhttprequest postdata


    【解决方案1】:

    我自己偶然解决了这个问题,我在服务器上激活了 mod_dumpio,一旦我关闭它,它就开始工作了。

    我不知道 mod_dumpio 做了什么来拒绝 XHR POST 但不是通用的 HTTP POST,但至少已经解决了。

    希望有一天这会对其他人有所帮助。

    (在旁注中,我意识到我的示例中的 postdata 查询格式不正确,应该是 « postdata_test= » 而不是 « postdata_test »,所以如果您遇到我的情况并想要运行相同的情况,请添加该等号我做过的测试)

    【讨论】:

      猜你喜欢
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      相关资源
      最近更新 更多