解析与访问 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}}]
How do I access every item in 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)
I have JSON data (added a newline for readability) returned as
[{"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}}]
How do I access each item in jQuery.
I tried doing something like (assume that /pendingorders returns 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')
},
});
});
This is the error I get in Firebug:
object is undefined
[Break On This Error] length = object.length,
jquery.js (line 605)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用当前的结构,我认为您只想要:
您有一个杂散的
, 'json'
作为each
的第三个参数,以及成功值后面的逗号(即好的,但可能是无意的)但是,由于 JSON 劫持。
如果结构是:
你原来的每一行:
将是正确的。
With the current structure, I think you just want:
You had a stray
, 'json'
as the third parameter toeach
, and a comma after the success value (which is okay but probably unintended)However, you may want to make the top level an object instead of an array, due to JSON hijacking.
If the structure were:
your original each line:
would be correct.
您将“json”作为参数传递给
each()
(注意缩进)。您通常可以在get()
上执行此操作,但ajax()
的工作方式不同 - 设置dataType
选项就足够了:请参阅 ajax方法文档供参考。
You're passing 'json' as a parameter to
each()
(watch the indentation). You can usually do that onget()
, butajax()
works differently - setting thedataType
option should suffice:See the ajax method documentation for reference.