我想用API来获取JSON格式的数据,并将它传递给jQuery来处理它。如何从jQuery访问此JSON结构中的数据?
我的JSON看起来像
{
"username": {
"id": 0001,
"name": "test",
"IconId": 000,
"Level": 00,
"revisionDate": 00000000
}
}
从PHP端,这是我的代码
$json = file_get_contents($url);
$json = json_encode($json);
从我的jQuery我可以用
<script type="text/javascript">
var ar = <?php echo $json ?>;
document.write(ar);
</script>
然而得到的数据,我希望能够从JSON获取特定的数据。例如名称。
我尝试使用jQuery.parseJSON这样
<script type="text/javascript">
var ar = <?php echo $json ?>;
ar = jQuery.parseJSON(ar);
document.write(ar.name);
</script>
而且我也试过
<script type="text/javascript">
var ar = <?php echo $json ?>;
ar = jQuery.parseJSON(ar);
document.write(ar[0].name);
</script>
我总是要么得到绝对没有(空白页),或我得到 “未定义”。
谢谢。
尝试文件撰写(ar.username.name); – Xinzoop
您还必须参考数据中存在的“用户名”。 '文件撰写(ar.username.name)'。 - [访问/进程(嵌套)对象,数组或JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) –
Try document.write(ar [0 ] .username.name); – Harminder