xhr.responseText returned null with POST
xhr.responseText returned null with POST
这是我的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
相关文章:
- Ajax Call with Post in PHP
- IE11 FormData AJAX Post with File 在 401 之后挂起
- ajax post with jquery to mongodb
- .post javascript with PHP 以启用 select 语句返回
- Wordpress: POST to .php with Ajax
- XDomainRequest POST with XML..我做错了什么
- 未定义的 ajax post with for 循环和字符串选择器
- Jquery ajax with google app engine post method
- jQuery document.ready with ajax $.post
- Ajax POST XMLHttpRequest() 无法发送参数 with & characther
- Laravel 5.2 Ajax POST TokenMismatchException with Valid CSRF
- POST with ajax, php, html
- Javascript HTTP POST with JSON data
- CKEditor post value with ajax post old value
- JavaScript for HTTP post XML with authentication
- X-editable with ASP MVC View,如何将提交的表单POST操作获取到控制器
- AngularJS $http.post with body
- Coffeescript Promise with Jquery Post
- xhr.responseText returned null with POST
- Angular - routeProvider with Post