【问题标题】:XMLHTTP request passing JSON string as raw post dataXMLHTTPrequest 将 JSON 字符串作为原始帖子数据传递
【发布时间】:2013-06-14 17:47:02
【问题描述】:

我的 JavasSript 发送请求:

var jax = new XMLHttpRequest();
jax.open("POST", "http://localhost/some.php", true);
jax.setRequestHeader("Content-Type", "application/json");
jax.send(JSON.stringify(jsonObj));
jax.onreadystatechange = function() {
    if(jax.readyState === 4) { console.log(jax.responseText);  }
}

现在我的 php 所做的只是:

print_r($HTTP_RAW_POST_DATA);
print_r($_POST);

原始帖子数据的输出是对象字符串,但帖子数组为空。

{"name" : "somename", "innerObj" : {} ... }
Array
(
)

我需要为 $_POST 变量以正确的格式获取它,而 jquery 不是一个选项。

【问题讨论】:

  • 你试过file_get_contents('php://input')吗?

标签: php ajax http-post


【解决方案1】:

对,因为 user1091949 发布了我的评论作为答案,这里又是同样的事情,所以 OP 可以选择谁的答案来批准(如果有效):

$json = json_decode(file_get_contents('php://input'));

此时,$json 将是stdClass 的一个实例...如果您更喜欢关联数组,只需将第二个参数传递给json_decode('{"json":"string"}', true);

顺便说一句:从不永远使用死亡的禁止错误抑制器:@。错误是为了帮助你,而不是为了惹恼你......

【讨论】:

  • 我发表了你的评论作为答案?
【解决方案2】:

您需要获取原始帖子数据:

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  exit;
}

$postdata = @file_get_contents("php://input");
$json = json_decode($postdata, true);

$json 将是一个包含您的 JSON 数据的关联数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多