我正在尝试构建一个从服务器获取数据并将其显示给用户的webapp。脚本每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;
}
});
}
答案 0 :(得分:7)
一种非常简单(但有点蹩脚)的解决方案是比较字符串表示:
if(JSON.stringify(a) != JSON.stringify(b)) { ... }
答案 1 :(得分:1)
您的代码每隔10秒发出警报,因为您的比较
if(data != old){ // data from the server is not same as old
每次都返回true。
您可以使用此库来比较javascript中的json https://github.com/prettycode/Object.identical.js 并将比较修改为
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)