我有一個與數據庫交談的servlet,然後返回一個有序的(ORDER BY時間)對象列表。在servlet部分,我有有序的JSONObject
//access DB, returns a list of User objects, ordered ArrayList users = MySQLDatabaseManager.selectUsers(); //construct response JSONObject jsonResponse = new JSONObject(); int key = 0; for(User user:users){ log("Retrieve User " + user.toString()); JSONObject jsonObj = new JSONObject(); jsonObj.put("name", user.getName()); jsonObj.put("time", user.getTime()); jsonResponse.put(key, jsonObj); key++; } //write out out.print(jsonResponse);
從日誌中我可以看到數據庫以正確的順序返回用戶對象。
在前端,我有
success: function(jsonObj){ var json = JSON.parse(jsonObj); var id = 0; $.each(json,function(i,item) { var time = item.time; var name = item.name; id++; $("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time + '</td><td>' + name + '</td></tr>'); }); },
但順序改變。
我只在返回的列表大小超過130個用戶時才注意到這一點。
我試過使用Firebug進行調試,Firebug中的「響應選項卡」顯示列表的順序與servlet中的日誌不同。
我做錯了什麼?
編輯:實例
{"0":{"time":"2011-07-18 18:14:28","email":"[email protected]","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"}, "1":{"time":"2011-07-18 18:29:16","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}, "2": ,..., "143":{"time":"2011-08-09 09:57:27","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"} ,..., "134":{"time":"2011-08-05 06:02:57","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
請給出一個你的JSON對象的例子。 JSON對象沒有與它們關聯的特定「順序」。爲此,您應該使用一個Array(它本身可以存儲在JSON對象中)。 – ghayes
嗨ghayes,謝謝你的提示(JSON對象沒有與它們相關的特定'順序')。我期待返回的對象與構建的順序相同。我仔細研究了Firebug的JSON對象,並注意到我可以使用鍵值來重新排列列表。 – user200340
如果你關心排序問題,我還在我的答案中寫了一些JavaScript來做到這一點。請享用! – ghayes