Parsing JSON in PHP
在PHP中解析JSON
My variable jsonvar is in the form of {"rating":"good"}
我的变量jsonvar采用{“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代码提交它,我对我的PHP(jsonproc.php)看起来有点困惑。
$.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.
使用alert(j.msg)显示“null”值。
Assuming that I am passing JSON in correctly, how can I point to the rating and get the value of "good"?
假设我正确地传递JSON,我如何指向评级并获得“好”的值?
Thanks
谢谢
EDIT
编辑
SOLVED, USING $_REQUEST I was able to get the JSON, however $_GET did not work.
已解决,使用$ _REQUEST我能够获得JSON,但$ _GET无效。
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?
另外,关键是使用$ decoding - > {'rating'}因为$ decode不再仅仅是一个我不认为的数组,或者它是一个diff类型的?
2 个解决方案
#1
3
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.
如果传递一个对象,jQuery将转换JSON,但是您将查询字符串与JSON混合。
Try:
尝试:
data: {js: jsonvar},
You may also need to do json_decode($_GET['js']).
您可能还需要执行json_decode($ _ GET ['js'])。
edit: You can double check what jQuery is POSTing with Firebug/Web Inspector. Easiest way to know for sure.
编辑:您可以使用Firebug / Web Inspector仔细检查jQuery正在POST的内容。最简单的方式来确定。
#2
-2
Try adding this to the top of your PHP file:
尝试将其添加到PHP文件的顶部:
header('Content-type: application/json');
#1
3
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.
如果传递一个对象,jQuery将转换JSON,但是您将查询字符串与JSON混合。
Try:
尝试:
data: {js: jsonvar},
You may also need to do json_decode($_GET['js']).
您可能还需要执行json_decode($ _ GET ['js'])。
edit: You can double check what jQuery is POSTing with Firebug/Web Inspector. Easiest way to know for sure.
编辑:您可以使用Firebug / Web Inspector仔细检查jQuery正在POST的内容。最简单的方式来确定。
#2
-2
Try adding this to the top of your PHP file:
尝试将其添加到PHP文件的顶部:
header('Content-type: application/json');