每次刷新时JSON数据都会更改 [英] JSON data changes on every refresh
问题描述
我收到了一个Ajax调用,该调用从json文件中获取数据.之后,我计算对象的长度并仅获取长度.一切正常.但是在刷新时,它不会以相同的顺序显示数据
I got an ajax call which fetches data from a json file. After which i calculate the length of the object and get only the length. Everything is working fine. But on refresh its not displaying the data in the same order
//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
console-2输出//此处正在发生更改
console-2 output //changes are happening here
Data-2:value-2
Data-1:value-1
Data-3:value-3
Data-4:value-4
在每次刷新时,我都会更改数据顺序.这也反映在我的html中.如果有人可以帮助
And on every refresh i get the data order changed. Which is reflected in my html too. If someone could hel
推荐答案
为什么不使用jQuery根据键对数据进行排序并执行所需的操作.我有自定义排序的粘贴代码,希望对您有用.
why you don't sort data based on key using jQuery and do operation what you want to do. i have paste code of custom sort please hope do needful for you.
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);
这篇关于每次刷新时JSON数据都会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!