【问题标题】:Javascript JSON comparisonJavascript JSON 比较
【发布时间】:2012-04-28 15:45:56
【问题描述】:

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

【问题讨论】:

  • 如何确定两个 javascript 对象的相等性:stackoverflow.com/questions/201183/…
  • 从不将字符串传递给setInterval()setTimeout()。这样做与使用eval() 一样糟糕,一旦使用变量,它就会导致代码不可读且可能不安全,因为您需要将它们插入字符串而不是传递实际变量。正确的解决方案是setInterval(function() { /* your code *) }, msecs);。这同样适用于setTimeout()。如果只想调用单个函数不带任何参数,也可以直接传函数名:setInterval(someFunction, msecs);(注意函数名后面有no()

标签: javascript jquery json compare


【解决方案1】:

您的代码每 10 秒提醒一次,因为您的比较

    if(data != old){ // data from the server is not same as old

每次都返回真。

你可以使用这个库来比较 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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 很好,但无论如何,这取决于属性的顺序是否重要
    • 或者最好不要字符串化,而是使用来自 ajax 请求的未解析的 responseText。
    • 在 chrome 开发工具中运行这个,看看这个解决方案是否失败。虽然旧,但数据具有相同的属性/值。 var old = {'a':1, 'b':2}, 数据 = {'b':2, 'a':1}; if(JSON.stringify(old) != JSON.stringify(data)) '比较失败';
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多