Parsing JSON in PHP
My variable jsonvar is in the form of {"rating":"good"}
Once I push it through with this $.ajax code to submit, I'm a bit confused at what my PHP (jsonproc.php) should look like.
$.ajax({
url: 'jsonproc.php',
data: {js:jsonvar},
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok){
alert(j.msg);
} else {
alert(j.msg);
}
}
});
I have it set up as 开发者_开发知识库
$decoded = $_GET['js'];
$response = array(
'ok' => true,
'msg' => $decoded['rating']);
However when I echo it back,
echo json_encode($response);
using alert(j.msg) shows a "null" value.
Assuming that I am passing JSON in correctly, how can I point to the rating and get the value of "good"?
Thanks
EDIT
SOLVED, USING $_REQUEST I was able to get the JSON, however $_GET did not work.
Also, the key was using $decoded->{'rating'} as $decoded is no longer just an array i don't think or rather it's a diff type of one?
It looks like you're mixing data types here:
data: "js="+jsonvar,
jQuery will convert JSON if you pass an object, but you're mixing query string with JSON.
Try:
data: {js: jsonvar},
You may also need to do json_decode($_GET['js']).
edit: You can double check what jQuery is POSTing with Firebug/Web Inspector. Easiest way to know for sure.
Try adding this to the top of your PHP file:
header('Content-type: application/json');
精彩评论