如何按照与请求相同的顺序对 AJAX 响应进行排序

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

本文关键字:AJAX 响应 排序 顺序 何按照 请求      更新时间:2023-09-26

我有一个对象,其属性按特定顺序排序。对于每个属性,我必须进行 AJAX 调用,并且我需要响应与对象顺序相同。或者至少在所有响应到达后以相同的顺序获取它。

编辑:如果这可能有帮助,jQuery是可用的。

我尝试在相关问题中应用建议,但没有成功。

我简化了我的功能:

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"

有趣的是:在Chrome中,响应顺序始终与请求顺序相同。在火狐中,它洗牌了。

对象不排序。如果你想要一个订单,那就发回一个数组。

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