xhr.responseText returned null with POST

xhr.responseText returned null with POST

本文关键字:with POST null returned responseText xhr      更新时间:2023-09-26

这是我的js的样子

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myajaxurl.com/lyric", true);
var data = "lyric";
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    console.log(xhr.responseText);
  }
}
xhr.send(data);

和我简单的php

 <?php 
        if( isset($_POST['lyric']) )
        { ?>
            <?php echo "test"; ?>
//it take sometime for my php to work and return the result, i do data scraping here
    <?php } ?>

我希望在console.log中看到'test',但我没有,ajax需要发送。为什么? ?

PHP在进行post请求时似乎无法解码没有值的单个参数。一个简单的解决方案是在参数名之后显式地添加=:

var data = "lyric=";

的例子:

// index.php
print_r($_POST);
// command line
// parameter name, not value
$ curl --data "lyric" http://localhost:8888/index.php
Array
(
)
// parameter name with empty value
$ curl --data "lyric=" http://localhost:8888/index.php
Array
(
    [lyric] =>
)

比较GET代替(与print_r($_GET)):

$ curl http://localhost:8888/index.php?foo
Array
(
    [foo] =>
)

您试图错误地访问数据。您需要像发出GET请求时那样传递参数。因此,在下面的代码中,可以通过存储所需数据的$_POST数组访问data变量。

JAVASCRIPT

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://myajaxurl.com/lyric", true);
    var data1 = "data=lyric";
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        console.log(xhr.responseText);
      }
    }
    xhr.send(data1);
PHP

 <?php 
   if( isset($_POST['data']) )
        {
            echo "test";
        } 
  ?>

编辑

标题问题可以这样解决

 var xhr = new XMLHttpRequest();
 xhr.open("POST", "http://myajaxurl.com/lyric", true);
 var data1 = "data=lyric";
 http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 http.setRequestHeader("Content-length", data1.length);
 http.setRequestHeader("Connection", "close");
 xhr.onreadystatechange = function() {
     if (xhr.readyState == 4) {
         console.log(xhr.responseText);
     }
}
xhr.send(data1);

来源:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php