jQuery getJSON data order varies across browsers
JSON data:
{"2":"Alpha","1":"Beta"}
The data format is fixed, i.e. I can't change it, I can only amend the javascript/jQuery code.
$.getJSON("www.myurl.com", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ', ' + val);
});
alert(items);
});
Chrome, IE9, and Opera display: 1, Beta,2, Alpha
Firefox and Safari display: 2, Alpha,1, Beta
Question 1: Which is correct?
Question 2: 开发者_C百科I want the data ordered as in Firefox and Safari. What's the easiest way for me to ensure Chrome, IE9, and Opera produce the same output as Firefox and Safari?
$.each
operates on javascript arrays (indexes are 0 based integers). The JSON you have shown is not an array. It's an associative array which is what javascript objects are. So:
$.getJSON("www.myurl.com", function(data) {
var items = [];
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
items.push(prop + ', ' + data[prop]);
}
}
alert(items);
});
Or if you want to use $.each
then use arrays, like this:
["Alpha", "Beta"]
and then:
$.getJSON("www.myurl.com", function(data) {
var items = [];
$.each(data, function(index, element))
items.push(index + ', ' + element);
}
alert(items);
});
no idea... but you can sort the array after the fact.
given the following output (simulated for testing)
var items = ["1, Beta", "2, Alpha"]
you can
items.sort(function(a,b){ return b.split(",")[0] - a.split(",")[0] })
i would rearrange your response to something more like this:
[
{
"key":"2",
"value":"Alpha"
},
{
"key":"1",
"value":"Beta"
}
]
using an array will ensure that the order is preserved.
精彩评论