php - 使用不带 jQuery 的 XMLHttpRequest 将 JSON 数据发送到 PHP

标签 php json post xmlhttprequest

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

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

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

POST 数组始终为空,但我可以看到 file_get_contents 返回的 JSON 字符串。这是怎么发生的?我做错了什么?

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"}

发送函数:

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
}

最佳答案

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) ?: [];

快速说明:您不应该发送包含 application/json 内容类型的字符集。这应该只与 text/* Content-Types 一起发送。

关于php - 使用不带 jQuery 的 XMLHttpRequest 将 JSON 数据发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9516019/

相关文章:

php - 使用空变量和格式化数字

javascript - 分别读取div中包含的输入值

python - 用 Python 中另一个 JSON 文件中的相应值替换 JSON 值

javascript - JQuery Post 将不起作用

php - 获取两个日期之间的数据并按各个日期分组

php - apache 停止响应然后崩溃

php - 当按下第二个提交按钮时,变量中的值消失

java - 在Java中发布XML并获取响应代码

php - 多对多 Doctrine : count left join collection

json - 使用多线程加载大型 JSON 文件/