Javascript JSON比较

问题描述:

我试图构建一个webapp从服务器获取数据并显示给用户。脚本每10秒从服务器获取数据,如果数据已更改,则警告用户。这是我现在使用的代码,但它每10秒警报数据是否已更改。

I am trying to build a webapp that gets data from server and shows it to user. Script gets data from server every 10 seconds and if data has changed it alerts user. This is the code I'm using now, but it alerts every 10 second whether the data has changed or not.

那么我该如何改变我的scipt来比较旧的JSON和新的JSON,看看他们是否不同,如果他们在更新前显示警报数据显示给用户?

So how do I need to alter my scipt to make it compare the old JSON and the new JSON and see if they are different, and if they are show alert before updating data shown to user?

$('#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;
        }
    });
}  


的方法是比较字符串表示:

A very easy (but kind of lame) solution is comparing the string representations:

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