这个问题可能是由于API的变化导致的,需要使用JSON.stringify()将数据转换为JSON字符串进行传输。此外,还需要将Content-Type设置为application/json,以便服务器能够正确解析数据。以下是一个示例:
Javascript代码:
var data = {"name": "John", "age": 30};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", "example.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(json);
PHP代码:
$data = json_decode(file_get_contents('php://input'), true);
echo $data['name'];
echo $data['age'];
通过将数据作为json变量传递,PHP可以正常解析和使用它们。
下一篇:Ajax看不到这个函数吗?