首页 > 解决方案 > 在 php 中获取 POSTed JSON 数组

问题描述

如何发送POST请求以及JSON数组main.php以返回 的值key_1?我下面的当前方法不起作用,我不知道如何解决这个问题。

script.js:

var array = {};
array["key_1"] = "obj_1";
array["key_2"] = "obj_2";
array["key_3"] = "obj_3";

var http = new XMLHttpRequest();
http.open("POST", "main.php");
http.onload = function () {
    document.querySelector("p").innerHTML = this.responseText;
}
http.send(array);

main.php:

<?php
    $params = json_decode(file_get_contents("php://input"));
    echo ($params["key_1"]);
?>

index.html:

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <p></p>
</body>
</html>

标签: javascriptphp

解决方案


file_get_contents()不解析内容。您需要通过json_decode().

<?php
    $params = json_decode(file_get_contents("php://input"), true);
    echo ($params["key_1"]);
?>

推荐阅读