JQuery: $ .getJSON sorting data in Chrome / IE?

I pass an associative array (id => val) using Ajax and get it using jQuery $ .getJSON, which read the data correctly and prepared the object. There is, however, a very annoying sorting problem.

It seems that in Chrome and IE, the data is sorted by the id part of the associated array. Therefore, if the array should be (5 => 'xxx', 3 => 'fff'), it actually becomes (3 => 'fff', 5 => 'xxx'). In FireFox, it works as expected, i.e. Not sorted.

Any ideas?

+1
javascript jquery sorting ajax getjson
Feb 21 '12 at 14:20
source share
4 answers

It seems the best way is to avoid associative arrays in general. When you want to send an associated array, just send it as two separate arrays - one of the keys and one of the values. Here is the PHP code for this:

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

and simple JavaScript code to do everything you need

  for (i=0; i < data['k'].length; i++) { console.log('key:' + data['k'][i] + ' val:' + data['v'][i]); } 
0
Feb 22 2018-12-22T00:
source share

You can add a leading value of 0 for all integer indices.

 var json = { '05' => 'xxx', '03' => 'fff' }; 
+2
Nov 09 '12 at 6:10
source share

Another option is to return the data as an array of objects. This ensures that the objects remain in the order in which you return them.

Edit:

Basically, for each key pair> click on the new array and json_encode on this array.

0
Feb 21 2012-12-21
source share

First of all, you should not assume any sorting of keys in an associative array. There are no guarantees of any sort order.

In any case, to work around this problem, you must sort the keys yourself.

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

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

-one
Feb 21 2018-12-12T00:
source share



All Articles