jQuery: $.getJSON sorting the data on Chrome / IE?

2019-05-30 08:54发布

问题:

I'm passing an associative array (id => val) using Ajax and receiving it with jQuery's $.getJSON which read the data properly and prepared the object. There is, however, very annoying sorting issue.

It appears that on Chrome and IE the data becomes sorted by the id part of the associate array. So if the array should be (5=> 'xxx', 3 => 'fff') it actually becomes (3 => 'fff',5=> 'xxx'). On FireFox it works as expected, i.e. not sorted.

Any ideas?

回答1:

You can add a leading 0 for all integer indexes.

var json = { '05' => 'xxx', '03' => 'fff' };


回答2:

Seems the best way is to avoid associative arrays at all. When you want to send an associate array simply send it as two separate arrays - one of keys and one of values. Here's the PHP code to do that:

    $arWrapper = array();
    $arWrapper['k'] = array_keys($arChoices);
    $arWrapper['v'] = array_values($arChoices);
    $json = json_encode($arWrapper);

and the simple JavaScript code to do whatever you'd like with it

            for (i=0; i < data['k'].length; i++) {
                console.log('key:' + data['k'][i] + ' val:' + data['v'][i]);
            }


回答3:

Another option is to return the data as an array of objects. That will ensure that the objects stay in the order that you return them.

Edit:

Basically, for each key > value pair, push it to a new array and json_encode that array.



回答4:

First of all, you shouldn't assume any kind of sorting of keys in an associative array. There are no guarantees of any sorting order.

Anyway, to get around the issue, you should sort the keys yourself.

http://jsfiddle.net/foxbunny/ZTXhp/

EDIT: Object.keys is EcmaScript 5 feature, so if your target browser does not support it, load up es5-shim (https://github.com/kriskowal/es5-shim).