简体   繁体   中英

How to sort AJAX response in the same order as request?

I have an object with its properties sorted in a certain order. For each property I have to make an AJAX call and I need the response to be in the same order as the object. Or at least get it in the same order after all responses have arrived.

EDIT: jQuery is available if this might help.

I have tried applying suggestions in related questions with no success.

I have simplified my function:

prefillTable : function (data) {
    console.log(data);
    // this is the order of properties I need in my response:
    // => Object {color: "blue", light: "led", type: "interior", size: "18"}

    for (var prop in data) {
        (
            function (key) {
                service.getAvailableValues(key, function (data) {
                    // this is where the sort order is missing right now
                    console.log(key);
                });
            }
        )(prop, data[prop]);
    }
}

// output order of console.log(key) is always different, for example:
// [11:53:12.099] => "type"
// [11:53:12.113] => "light"
// [11:53:12.120] => "color"
// [11:53:12.158] => "size"

Funny thing: In Chrome response order is always the same as request order. In Firefox it shuffles.

Objects are not ordered. If you want an order, then send back an array instead.

 [ 
    { "name": "color", "value": "blue"},
    { "name": "light", "value": "led" },
    etc
 ]

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