使用 XMLHttpRequest w/o jQuery 将 JSON 数据发送到 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9516019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:59:43  来源:igfitidea点击:

Send JSON data to PHP using XMLHttpRequest w/o jQuery

phpjsonpostxmlhttprequest

提问by Simon

I am trying to send JSON data from a form using the XMLHttpRequest object. I can send the data using the following function. There are no errors displayed in FireBug and the JSON-data in the request is displayed well formed by FireBug.

我正在尝试使用 XMLHttpRequest 对象从表单发送 JSON 数据。我可以使用以下功能发送数据。FireBug 中没有显示错误,并且请求中的 JSON 数据由 FireBug 正确显示。

However, I send the data to echo.php, what simply returns the content:

但是,我将数据发送到echo.php,它只是返回内容:

<?php
print_r($_POST);
print_r($_GET);
foreach (getallheaders() as $name => $value) {
    echo "$name: $value\n";
}
echo file_get_contents('php://input');
?>

The POST-array is always empty, but I can see the JSON string returned by file_get_contents. How does that happen? What am I doing wrong?

POST 数组始终为空,但我可以看到 .json 返回的 JSON 字符串file_get_contents。怎么会这样?我究竟做错了什么?

output of echo.php

echo.php 的输出

Array
(
)
Array
(
)
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Referer: http://localhost/form.html
Content-Length: 88
Cookie: {{..to much data..}}
Pragma: no-cache
Cache-Control: no-cache
{"type":"my_type","comment":"commented"}

the sending function:

发送函数:

function submit(){
    var data={};
    data.type=document.form.type.value;
    data.comment=document.form.comment.value;

    //get right XMLHttpRequest object for current browsrer
    var x=ajaxFunction();

    var string = JSON.stringify(data);

    x.open('POST','echo.php',true);
    x.setRequestHeader('Content-type','application/json; charset=utf-8');
    x.setRequestHeader("Content-length", string.length);
    x.setRequestHeader("Connection", "close");

    x.onreadystatechange = function(){
        if (x.readyState != 4) return;
        if (x.status != 200 && x.status != 304) {
            alert('HTTP error ' + req.status);
            return;
        }

        data.resp = JSON.parse(x.responseText);
        if(data.resp.status=='success'){
            alert('That worked!');
        }else{
            alert('That didn\'t work!');
        }
    }
    x.send(string);

    return false; //prevent native form submit
}

采纳答案by artragis

You forgot to name your variables in the send function. The good way to use it is

您忘记在发送函数中命名变量。使用它的好方法是

x.send('name1='+string+'&name2=value2'); 

Given that, I think you will have to change the content-length header. I don't think it is usefull to send it.

鉴于此,我认为您将不得不更改内容长度标头。我认为发送它没有用。

One another thing you can do is try with GET method. You can also try to change your content-type header by that one :

您可以做的另一件事是尝试使用 GET 方法。您还可以尝试通过该标题更改您的内容类型标题:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")

回答by rich remer

PHP does not process JSON requests automatically like it does with form-encoded or multipart requests. If you want to use JSON to send requests to PHP, you're basically doing it correctly with file_get_contents(). If you want to merge those variables into your global $_POST object you can, though I would not recommend doing this as it might be confusing to other developers.

PHP 不会像处理表单编码或多部分请求那样自动处理 JSON 请求。如果您想使用 JSON 向 PHP 发送请求,那么使用 file_get_contents() 基本上是正确的。如果您想将这些变量合并到您的全局 $_POST 对象中,您可以,但我不建议这样做,因为它可能会让其他开发人员感到困惑。

// it's safe to overwrite the $_POST if the content-type is application/json
// because the $_POST var will be empty
$headers = getallheaders();
if ($headers["Content-Type"] == "application/json")
    $_POST = json_decode(file_get_contents("php://input"), true) ?: [];

Quick note: you should not be sending a charset with your Content-Type for application/json. This should only be sent with text/* Content-Types.

快速说明:您不应该为 application/json 发送带有 Content-Type 的字符集。这应该只与 text/* Content-Types 一起发送。