gpt4 book ai didi

javascript - AJAX 请求已提交,但未收到 POST 值

转载 作者:行者123 更新时间:2023-11-27 23:46:17 26 4
gpt4 key购买 nike

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

谢谢
雅克·马莱

最佳答案

这个例子有效:

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

关于javascript - AJAX 请求已提交,但未收到 POST 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com