XMLHTTP请求将JSON字符串作为原始POST数据传递

4

我的JavaScript发送请求:

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);

从原始的POST数据中得到的输出是对象字符串,但POST数组为空。
{"name" : "somename", "innerObj" : {} ... }
Array
(
)

我需要将数据以正确的格式传递给$_POST变量,而jQuery不是一个选项。


你尝试过使用 file_get_contents('php://input') 吗? - Elias Van Ootegem
2个回答

6

好的,既然user1091949将我的评论发布为答案,这里再次提供相同的内容,这样OP就可以选择哪个答案来批准(如果它起作用):

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

此时,$json 将是 stdClass 的一个实例...... 如果你希望使用关联数组,只需向 json_decode('{"json":"string"}', true); 传递第二个参数。

顺便提一下:千万不要 使用被禁止的错误抑制符 @。错误是为了帮助你而不是让你烦恼...


我把你的评论发布为答案了吗? - user1091949

0
你需要获取原始的POST数据:
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  exit;
}

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接