解析&访问JSON数据

时间:2011-04-04 20:41:41

标签: javascript jquery json parsing

我有

返回的JSON数据(添加了可读性换行符)
[{"pk": 7, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, "transaction_id": "2008010661301935441", "quantity": 2}},
{"pk": 8, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "9count1%1", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:14", "dish": 9, "transaction_id": "2008010661301935454", "quantity": 1}}]

如何访问jQuery中的每个项目。

我尝试过这样的事情(假设/ pendingorders返回JSON)

$(document).ready(function (){ 
jQuery.ajax({
    cache: false,
    url: "/pendingorders",
    type: "GET",
    success: function(json) {
        $.each(json.results, function(i,dish){
            alert(dish.pk); 
            },'json')
        },  
    }); 
});

这是我在Firebug中遇到的错误:

object is undefined
[Break On This Error] length = object.length,
jquery.js (line 605)

2 个答案:

答案 0 :(得分:2)

根据目前的结构,我认为你只想:

jQuery.ajax({
    cache: false,
    url: "/pendingorders",
    type: "GET",
    success: function(json) {
        $.each(json, function(i,dish){
              alert(dish.pk); 
        });
    }); 
});

您有一个迷路, 'json'作为each的第三个参数,以及一个逗号后面的成功值(可以,但可能是无意的)

但是,由于JSON hijacking,您可能希望将顶级设为对象而不是数组。

如果结构是:

{"results":
[{"pk": 7, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, "transaction_id": "2008010661301935441", "quantity": 2}},
{"pk": 8, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "9count1%1", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:14", "dish": 9, "transaction_id": "2008010661301935454", "quantity": 1}}]}

你原来的每一行:

$.each(json.results, function(i,dish){

是正确的。

答案 1 :(得分:2)

您将'json'作为参数传递给each()(观看缩进)。您通常可以在get()上执行该操作,但ajax()的工作方式不同 - 设置dataType选项应该足够了:

jQuery.ajax({
    cache: false,
    url: "/pendingorders",
    type: "GET",
    dataType: 'json',
    success: function(json) {
        $.each(json.results, function(i,dish){
            alert(dish.pk); 
        });
    }
});

请参阅ajax method documentation以供参考。