每次刷新时JSON数据都会发生变化

时间:2015-07-30 11:51:25

标签: jquery ajax

我有一个从json文件中获取数据的ajax调用。之后我计算物体的长度并获得长度。一切都很好。但是在刷新时它没有以相同的顺序显示数据

//url i get from another file.which is a object hardcoded.
var initialsource = [{ "data": [] }];
var totallength = url.length;
var j = 0; // dummy variable to check whether the data has reached full length;

$.each(url,function(keys,values){   
    console.log(keys);  // get the keys which is mapped to json file location.// 1st console.
    $.get(values, function(jsondata) { // ajax call made to get the data
        console.log(keys); // 2nd console.
        initialsource[0].data.push({ 
            "datasource": keys,
            "values": jsondata[0].xxx.length
        })           
        j++;
        if (j == totallength) {
            //render data to html
        }
    })    
})

首次刷新

console-1输出

Data-1:value-1
Data-2:value-2
Data-3:value-3
Data-4:value-4

console-2输出

Data-1:value-1
Data-2:value-2
Data-3:value-3
Data-4:value-4

第二次刷新

console-1输出

Data-1:value-1
Data-2:value-2
Data-3:value-3
Data-4:value-4

console-2输出//这里发生了变化

Data-2:value-2
Data-1:value-1
Data-3:value-3
Data-4:value-4

每次刷新我都会改变数据顺序。这也体现在我的html中。如果有人可以帮忙

2 个答案:

答案 0 :(得分:0)

这是因为$.get请求是异步的。这意味着它们不能保证按发送顺序返回。如果您需要维护订单,则需要在请求完成后sort()对象。试试这个:

var requests = [];

$.each(url, function(keys, values) {   
    requests.push($.get(values, function(jsondata) {
        initialsource[0].data.push({ 
            "datasource": keys,
            "values": jsondata[0].xxx.length
        });
    }));  
})

$.when.apply(this, requests).done(function() {
    var sortedData = initialsource.sort(function(a, b) {
        return a.values < b.values;
    });
    // sortedData is now in length order, use it as required here...
});

答案 1 :(得分:0)

为什么你不使用jQuery根据键对数据进行排序,并按照你想要的操作进行操作。我有自定义类型的粘贴代码,请希望对你有用。

jQuery.fn.sort = function() {  
    return this.pushStack( [].sort.apply( this, arguments ), []);  
};  

 function sortLastName(a,b){  
     if (a.l_name == b.l_name){
       return 0;
     }
     return a.l_name> b.l_name ? 1 : -1;  
 };  
  function sortLastNameDesc(a,b){  
     return sortLastName(a,b) * -1;  
 };
var people= [
{
"f_name": "john",
"l_name": "doe",
"sequence": "0",
"title" : "president",
"url" : "google.com",
"color" : "333333",
}]

sorted=$(people).sort(sortLastNameDesc);