简体   繁体   English

XMLHttpRequest 不发送 POST 数据

[英]XMLHttpRequest not sending POST data

I trying to send POST data to PHP file using XMLHttpRequest.我尝试使用 XMLHttpRequest 将 POST 数据发送到 PHP 文件。 The URL is right but PHP can't catch any of sent data and just back a null response. URL 是正确的,但 PHP 无法捕获任何发送的数据,只能返回 null 响应。

I'm using pure javascript from client and PHP 7.1 on server我使用来自客户端的纯 javascript 和服务器上的 PHP 7.1

My PHP:我的 PHP:

$data->msg = 'PHP is working';
$data->user = $_POST['user'];
$data->pass = $_POST['pass'];
echo json_encode($data);

My Javascript:我的 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: myUser, pass: myPass}

// But just recive: {msg: "PHP is working", user: null, pass: null}

I expect this response: {msg: "PHP is working", user: myUser, pass: myPass} But just recive this: {msg: "PHP is working", user: null, pass: null}我希望得到这样的响应:{msg: "PHP is working", user: myUser, pass: myPass} 但只要收到这个:{msg: "PHP is working", user: null, pass: null}

As you can see PHP $_POST can't catch my sent post data and just back null.如您所见,PHP $_POST 无法捕获我发送的帖子数据,只能返回 null。 What's worng??穿什么??

The problem is in your Content-Type.问题出在您的内容类型中。 If you use application/json the PHP won't parse the post data into $_POST variable.如果您使用application/json PHP 不会将发布数据解析为 $_POST 变量。 You have to send them as form data to have PHP parse it.您必须将它们作为表单数据发送,让 PHP 解析它。

See this question for more info Send POST data using XMLHttpRequest有关更多信息,请参阅此问题使用 XMLHttpRequest 发送 POST 数据

Alternatively you can use file_get_contents("php://input") to get the raw body of HTTP request and parse the json with json_decode .或者,您可以使用file_get_contents("php://input")获取 HTTP 请求的原始正文并使用 json_decode 解析json_decode

Example with file_get_contents and json_decode file_get_contents 和 json_decode 的示例

PHP Code: PHP 代码:

$in = file_get_contents('php://input');
$decoded = json_decode($in, true);
$data = new stdClass();
$data->msg = 'PHP is working';
$data->user = $decoded['user'];
$data->pass = $decoded['pass'];
echo json_encode($data);

JS Code: JS代码:

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(JSON.stringify(data));
    return false;

Please notice that you need to JSON.stringify the data object before passing it as argument to send() method.请注意,您需要JSON.stringify数据 object 在将其作为参数传递给send()方法之前。 Otherwise the data are not send correctly.否则数据无法正确发送。

To receive json in php you need to read request body:要在 php 中接收 json,您需要阅读请求正文:

$request = json_decode(file_get_contents('php://input'), true);

$data->msg = 'PHP is working';
$data->user = $request['user'];
$data->pass = $request['pass'];

echo json_encode($data);

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

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