2015-10-15 71 views
1

我正在处理某些事情,并且我有一个非常奇怪的问题。我提出一个AJAX请求像以下:AJAX请求提交,但不接收POST值

x = new XMLHttpRequest(); 
x.open('POST', url, true); 
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
x.onload = function(){ 
    console.log(x.responseText); 
}; 
x.send(data); 

的问题是,当我提交请求时,PHP没有收到POST值。该data变量看起来像以下:

Object { wordtype: "noun", word: "computer" } 

而且PHP像以下:

if(!isset($_POST['wordtype']) || !isset($_POST['word'])){ 
    echo "error 1"; 
    exit; 
} else { 
    $wordlist = json_decode(file_get_contents("words.json"), true); 
    $wordlist[$_POST['word']] = $_POST['wordtype']; 
    file_put_contents("words.json", json_encode($wordlist)); 
    echo "success"; 
} 

x.responseText值总是error 1;

谢谢
雅克·玛莱

+0

你的意思是使用'onreadystatechange',而不是'onload'?你也应该使用'application/json' Content-Type并在你发送的对象上使用'JSON.stringify'。 –

+0

@RalphWiggum http://stackoverflow.com/a/14946525/5305938 –

回答

1

这个例子的工作原理:

var http = new XMLHttpRequest(); 
var url = "ajax.php"; 
var params = "wordtype=noun&word=computer"; 
http.open("POST", url, true); 

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
http.setRequestHeader("Content-length", params.length); 
http.setRequestHeader("Connection", "close"); 

http.onreadystatechange = function() {//Call a function when the state changes. 
    if(http.readyState == 4 && http.status == 200) { 
     alert(http.responseText); 
    } 
} 
http.send(params); 
+0

非常感谢。我认为问题在于我使用对象作为数据发送而不是参数字符串,并且发送了错误的标题。 –