Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  146] [ 7]  / answers: 1 / hits: 20172  / 13 Years ago, tue, august 9, 2011, 12:00:00

I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have




//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);


From the log I can see that the database returns User objects in the correct order.



At the front-end, I have




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>');
});

},


But the order is changed.



I only noticed this when the returned list has large size (over 130 users).



I have tried to debug using Firebug, the response tab in Firebug shows the order of the list is different with the log in the servlet.



Did i do anything wrong?



EDIT: Example




{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}}

More From » jquery

 Answers
21

As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):



 jsonObj = 
{ items:
[ { name: Stack, time: ... },
{ name: Overflow, time: ... },
{ name: Rocks, time: ... },
... ] };


This structure will ensure that your objects are inserted in the proper sequence.



Based on the JSON you have above, you could place the objects into an array and then sort the array.



 var myArray = [];
var resultArray;

for (var j in jsonObj) {
myArray.push(j);
}

myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });

for (var i = 0; i < myArray.length; i++) {
resultArray.push(jsonObj[myArray[i]]);
}

//resultArray is now the elements in your jsonObj, properly sorted;


But maybe that's more complicated than you are looking for..


[#90721] Monday, August 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hugo

Total Points: 21
Total Questions: 120
Total Answers: 107

Location: Belarus
Member since Tue, Jul 20, 2021
3 Years ago
;