我尝试使用 XMLHttpRequest 将 POST 数据发送到 PHP 文件。URL 是正确的,但 PHP 无法捕获任何发送的数据,只能返回空响应。
我在客户端使用纯 JavaScript,在服务器上使用 PHP 7.1
我的PHP:
$data->msg = 'PHP is working';
$data->user = $_POST['user'];
$data->pass = $_POST['pass'];
echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
我的 JavaScript:
var data = { 'user': 'myUser', 'pass': 'myPass' };
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myurl', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var res = JSON.parse(xhr.response);
console.log(res);
}
};
xhr.send(data);
// Expected output: {msg: "PHP is working", user: …Run Code Online (Sandbox Code Playgroud)