我正在做一些事情,我有一个非常奇怪的问题。我提交了一个如下的AJAX请求:
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
;
谢谢你 Jacques Marais
答案 0 :(得分: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);