2011-04-04 60 views
0

我JSON数据(增加了可读性换行)返回解析和访问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

在当前的结构,我觉得你只是想:

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

你有一个流浪, 'json'作为的第三个参数,以及成功值后的逗号(这是可以的,但可能是无意的)

但是,由于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){ 

是正确的。

+0

感谢您提供丰富的答案。我认为“.results”是一些使其可迭代的方法。 – 2011-04-05 03:55:13

+0

如果我们可以做json劫持,我想知道当我在django中序列化数据库查询的结果时为什么会得到这样的结果。他们应该为此做点事情。 – 2011-04-05 03:58:00

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参考。

+0

我相信这是正确的答案。我只是想补充一点,如果你配置你的服务器端'/ pendingorders'代码来响应'application/json' HTTP头部,jQuery将自动将响应视为JSON并反序列化它,而不指定dataType。同样的结果,但更容易一些。 – 2011-04-05 01:06:42

+0

我返回json作为mimetype ='application/json',所以我不需要dataType。真正的错误是“.results”不应该在那里。我写了它,因为我认为这是一种可迭代的方法。 – 2011-04-05 03:58:30