我试图建立一个网络应用程序,从服务器获取数据,并显示给用户。脚本每10秒从服务器获取一次数据,如果数据发生更改,它会向用户发出警报。这是我现在使用的代码,但它每隔10秒就会发出一次数据是否发生更改的警报。
那么,在更新显示给用户数据之前,我需要如何修改我的scipt,使其比较旧的JSON和新的JSON,并查看它们是否不同,以及它们是否显示警报?
$('#ListPage').bind('pageinit', function(event) {
getList1();
});
setInterval ( "getList1()", 10000 );
var old = "";
function getEmployeeList1() {
$.getJSON(serviceURL + 'getemployees.php?' + formArray, function(data) {
if(data != old){ // data from the server is not same as old
$('#nollalista li').remove();
keikka = data.key;
$.each(keikka, function(index, lista) {
$('#nollalista').append('<li><a href="employeedetails.html?id=' + lista.IND + '">' +
'<h4>' + lista.OSO + '</h4>' +
'<p>' + lista.AIKA + '</p>' +'</a></li>');
});
$('#nollalista').listview('refresh');
if(old != "")
alert("New data!");
old = data;
}
});
}
发布于 2012-04-17 09:54:17
一个非常简单(但有点差劲)的解决方案是比较字符串表示:
if(JSON.stringify(a) != JSON.stringify(b)) { ... }
发布于 2012-04-17 10:26:38
您的代码每10秒发出一次警报,因为您的比较
if(data != old){ // data from the server is not same as old
每次都返回true。
您可以使用该库来比较javascript https://github.com/prettycode/Object.identical.js中的json,并将该比较修改为
if(!Object.identical(data,old)){ // data from the server is not same as old
用法:
var a = { x: "a", y: "b" },
b = { x: "a", y: "b" },
c = { y: "b", x: "a" },
d = { x: "Chris", y: "Prettycode.org", developerYears: [1994, 2011] },
e = { y: "Prettycode.org", developerYears: [1994, 2011], x: "Chris" };
f = { y: "Prettycode.org", developerYears: [2011, 1994], x: "Chris" };
console.log(Object.identical(a, b)); // true (same properties and same property values)
console.log(Object.identical(a, c)); // true (object property order does not matter, simple)
console.log(Object.identical(d, e)); // true (object property order does not matter, complex)
console.log(Object.identical(d, f)); // false (arrays are, by definition, ordered)
https://stackoverflow.com/questions/10188931
复制相似问题