问题
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