以下是我的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 } ?>
我希望看到&#39;测试&#39;在console.log但我没有,ajax需要发送。为什么??
答案 0 :(得分:0)
您试图错误地访问数据。您需要传递参数,就像您在发出GET请求时一样。因此,在下面的代码中,可以通过$ _POST数组访问数据变量,该数组存储您想要的数据。
<强> 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
答案 1 :(得分:0)
在执行发布请求时,PHP似乎无法解码没有值的单个参数。一个简单的解决方案是在参数名称后面显式添加=
:
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] =>
)