Javascript JSON 比较 [英] Javascript JSON comparison

查看:39
本文介绍了Javascript JSON 比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个从服务器获取数据并将其显示给用户的 web 应用程序.脚本每 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)) { ... }

这篇关于Javascript JSON 比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆