我得到了一个ajax调用,它从json文件中获取数据。在此之后,我计算对象的长度,并只得到长度。一切都很好。但是在刷新时,它没有按照相同的顺序显示数据。
//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
}
})
})用于第一次刷新
控制台-1输出
Data-1:value-1
Data-2:value-2
Data-3:value-3
Data-4:value-4控制台-2输出
Data-1:value-1
Data-2:value-2
Data-3:value-3
Data-4:value-4用于二次刷新的
控制台-1输出
Data-1:value-1
Data-2:value-2
Data-3:value-3
Data-4:value-4控制台-2输出//更改正在这里发生
Data-2:value-2
Data-1:value-1
Data-3:value-3
Data-4:value-4每次刷新时,我都会更改数据顺序。这也反映在我的html中。如果有人能
发布于 2015-07-30 11:58:52
这是因为$.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...
});发布于 2015-07-30 12:01:04
为什么不使用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);https://stackoverflow.com/questions/31723032
复制相似问题