【问题标题】:AJAX request submits, but doesn't recieve POST valuesAJAX 请求提交,但未收到 POST 值
【发布时间】:2016-01-14 03:18:40
【问题描述】:

我正在做一些事情,但我遇到了一个非常奇怪的问题。我提交了一个 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

谢谢
雅克·玛莱

【问题讨论】:

  • 您的意思是使用onreadystatechange 而不是onload?您还应该在要发送的对象上使用application/json Content-Type 和JSON.stringify

标签: javascript php ajax


【解决方案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);

【讨论】:

  • 非常感谢。我认为问题在于我使用对象作为数据发送而不是参数字符串,并且我发送了错误的标头。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2018-09-14
  • 2015-07-25
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多