php - 为什么在发出带有发布数据的请求后,PHP 中的 $_POST 数组为空

标签 php javascript ajax post

我使用发布数据向页面 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 来检查它

最佳答案

您传递给 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);

关于php - 为什么在发出带有发布数据的请求后,PHP 中的 $_POST 数组为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003711/

相关文章:

php - 如何在 Laravel 中编辑和保存自定义配置文件?

javascript - 显示来自 Firestore 时间戳的日期(不是时间)

javascript - 为什么 Chrome console.log 以如此烦人的方式显示 String 对象?

php - WooCommerce 结账字段未显示正确的错误消息

PHP 我在这段代码中遇到错误

Java 编码问题与 Ñ

ajax - JSF f :ajax listener not called

javascript - 使用 AJAX POST 请求发送自定义 HTTP 正文

php - 将\r\n 替换为 <br/>

javascript - 向 JSON 添加一行