XMLHTTP request passing JSON string as raw post data

谁都会走 提交于 2020-01-03 15:56:58

问题


My JavasSript sends the request:

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

Right now all my php does is:

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

The output from the raw post data is the object string, but the post array is empty.

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

I need to get it in the proper format for the $_POST variable, and jquery isn't an option.


回答1:


Right, since user1091949 posted my comment as an answer, here's the same thing again, so OP can choose who's answer to approve (if it worked):

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

At this point, $json will be an instance of the stdClass... If you prefer an associative array, just pass a second parameter to json_decode('{"json":"string"}', true);

BTW: Never, Ever use the forbidden error-suppressor of death: @. Errors are there to help you, not to annoy you...




回答2:


You need to get the raw post data:

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

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

$json will be an associative array containing your JSON data.



来源:https://stackoverflow.com/questions/17114380/xmlhttp-request-passing-json-string-as-raw-post-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!