【问题标题】:Why is $_POST array empty in PHP after an a request with post data为什么 PHP 中的 $_POST 数组在请求发布数据后为空
【发布时间】:2011-04-29 13:22:14
【问题描述】:

我使用发布数据向页面 getremote.php 发出发布请求,但 $_POST 数组似乎为空。如果有人能告诉我我做错了什么,将不胜感激。

发出请求的javascript代码是

var postdata = "Content-Type: application/x-www-form-urlencoded\n\nedits=" + this.createEditXMLtext(this.editXMLstruct);
 var xmlhttp;
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
  dispmes("processing edits");
 xmlhttp.open("POST",userProfile.homeurl + "?remoteurl=" + userProfile.homeurl + "&cmdeditprofile&password=password",false);

 xmlhttp.send(postdata);

 var response = xmlhttp.responseXML;

this.createEditXMLtext(this.editXMLstruct) 只是创建一个字符串

我以前没有遇到过这个问题,并且似乎没有与发布类似问题的其他人相同的解决方案。 userProfile.homeurl + "处的php代码是

header("Content-type: text/xml");
 $query = '';                  
    foreach( $_POST as $key => $value ){ 
  $query .= "$key=$value&";
 }
 echo do_post_request($_GET['remoteurl'] . $qstring,$query);

但字符串 $query 始终为空 - 我通过在文件底部添加 echo $query 来检查它

【问题讨论】:

  • 你 100% 确定 POST 是空的吗? print_r($_POST); 产生了什么?
  • 我猜应该是Header信息必须和body分开两个\r\n,而不仅仅是\n。 HTTP 1.1 规范: generic-message = start-line *(message-header CRLF) CRLF [ message-body ] start-line = Request-Line |状态行 CRLF = \r\n
  • 您当然应该考虑使用 jQuery、Dojo 或 YUI 等 javascript 框架来处理您的 AJAX 请求。

标签: php javascript ajax post


【解决方案1】:

您传递给send() 的值应该是整个帖子正文,并且您在其中包含了一个标题。当该主体到达 PHP 时,它将无法将其解析为编码的表单数据。

改为通过调用setRequestHeader()来设置数据类型

 //create the postdata, taking care over the encoding
 var postdata = "edits=" + encodeURI(this.createEditXMLtext(this.editXMLstruct));

 //let server know the encoding we used for the request body
 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

 //and here we go 
 xmlhttp.send(postdata);

【讨论】:

    【解决方案2】:

    我从来没有见过这样的做法,尝试通过XMLHttpRequest.setRequestHeader() 将您的标题与 POST 正文分开设置,如下所示:

    var postdata = "edits=" + this.createEditXMLtext(this.editXMLstruct);
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    dispmes("processing edits");
    xmlhttp.open("POST", userProfile.homeurl + "?remoteurl=" + userProfile.homeurl + "&cmdeditprofile&password=password",false);
    xmlhttp.send(postdata);
    var response = xmlhttp.responseXML;
    

    【讨论】:

      猜你喜欢
      • 2016-03-01
      • 2016-08-29
      • 2018-07-09
      • 1970-01-01
      • 2019-06-27
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多