简体   繁体   中英

$.ajax get an object after json_encode($arr) from php, but how to get key and value in jQuery?

1

In PHP:

$arr = array( 10=>"ten", 5=>"five", 2=>"two"); return json_encode($arr);

In JS - $.ajax():

success: function(data){ console.log(data);}

2

What I see in console is :

Object {2: "two", 5: "five", 10: "ten"} ,

I want to use for(var i=0; i< data.length,i++) but failed.

Finally it works in this way : for(var i in data)

3

My Question: Why the array is sorted? I want the array to keep unsorted.

Anyone helps me?

JSON cannot represent a sparse array, which is what your data would be if it did.
So you get an object instead of an array and the is no standard that says object properties has to sorted in any specific way or not sorted at all.
You can try having your data in 2 arrays

$arr = array( 'indecies'=>array(10,5,2), 'values'=>array("ten","five","two") ); 
return json_encode($arr);
for(var i=0; i< data.indecies.length,i++){
    // do something with
    //data.indecies[i]
    //data.values[i]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM