【问题标题】:Javascript + PHP $_POST array emptyJavascript + PHP $_POST 数组为空
【发布时间】:2010-04-20 07:19:08
【问题描述】:

尝试通过 xmlhttp.open("POST", "url", true) (javascript) 向服务器发送 POST 请求时,我得到一个空的 $_POST array

Firebug 显示正在发送数据。这是来自 Firebug 的数据字符串:a=1&q=151a45a150...。但是$_POST['q'] 什么也没返回。

有趣的是file_get_contents('php://input') 确实有我的数据(上面的字符串),但是 PHP 不知何故无法识别它。尝试了 $_POST 和 $_REQUEST,没有任何效果。

正在发送的标头:

POST /test.php HTTP/1.1
Host: website.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401        Firefox/3.6.3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://website.com/
Content-Length: 156
Content-Type: text/plain; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache

感谢您的任何建议。

【问题讨论】:

    标签: php javascript http-post


    【解决方案1】:

    您似乎缺少正确的 Content-Type 标头。这是 POST 请求所必需的:

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
    

    【讨论】:

      【解决方案2】:

      发送一个

      Content-Type: application/x-www-form-urlencoded
      

      标题而不是text/plain

      【讨论】:

        【解决方案3】:

        你必须这样写:

        xmlhttp.open("POST", "script.php", true);
        xmlhttp.send("foo=bar&answer=42");
        

        【讨论】:

          【解决方案4】:

          只是花了几个小时试图找到解决这个问题的方法。

          我犯了一个愚蠢的错误,即连接几个我想作为参数的字符串,然后在整个过程中调用encodeURIComponent。这当然意味着

          foo=bar&this=that
          

          成为

          foo%3Dbar%26this%3Dthat
          

          这对于 PHP 脚本来说当然是胡言乱语。虽然我怀疑会有很多人会做这种愚蠢的事情,但我希望它可以避免我刚刚给自己带来的头痛......

          【讨论】:

            猜你喜欢
            • 2016-06-20
            • 1970-01-01
            • 2015-06-24
            • 2016-05-17
            • 2010-11-19
            • 1970-01-01
            • 2017-01-07
            • 2011-05-02
            • 1970-01-01
            相关资源
            最近更新 更多