简体   繁体   English

AJAX请求提交,但不接收POST值

[英]AJAX request submits, but doesn't recieve POST values

I am working on something and I have a very weird problem. 我正在做某事,但有一个很奇怪的问题。 I submit an AJAX request like following: 我提交如下的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);

The problem is, when I submit the request, the PHP doesn't receive the POST values. 问题是,当我提交请求时,PHP没有收到POST值。 The data variable looks like following: data变量如下所示:

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

And the PHP like following: 和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";
}

The value of x.responseText is always error 1 ; x.responseText的值始终为error 1

Thank You 谢谢
Jacques Marais 雅克·马莱斯(Jacques Marais)

This example works: 此示例有效:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM