Javascript JSON比较

我正在尝试构建一个从服务器获取数据并将其显示给用户的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('
  • ' + '

    ' + lista.OSO + '

    ' + '

    ' + lista.AIKA + '

    ' +'
  • '); }); $('#nollalista').listview('refresh'); if(old != "") alert("New data!"); old = data; } }); }

    一个非常简单(但有点蹩脚)的解决方案是比较字符串表示:

     if(JSON.stringify(a) != JSON.stringify(b)) { ... } 

    您的代码每隔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)