2011-04-04 41 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