使用jQuery检测JSON数组中有多少元素发生了变化

Detect how many elements have changed in JSON array with jQuery

本文关键字:多少 元素 发生了 变化 jQuery 检测 JSON 数组 使用      更新时间:2023-09-26

我对web开发非常陌生,所以这对你来说可能是微不足道的:

我正在建造一堵墙,墙上展示着100幅微型风景画的马赛克。我从一个远程JSON中获得这些图片的url,该JSON只包含最近上传的100张图片,从最近的开始。JSON是不断更新的。

JSON结构:

[
{
    "name": "Blue Mountains",
    "url": "http://foo.com/url-to-picture", // <- Most recent
    "location": "Canada"
},
{
    "name": "Yellow Lake",
    "url": "http://foo.com/url-to-picture", // <- Second most recent
    "location": "Greece"
}, ...
]

我想检查JSON每10秒,并检测是否有新的图片上传,如果有,我想知道有多少,然后用新的照片从墙上替换旧的照片。

我能想到的只有:

function getNewPictures() {
    $.getJSON("http://bar.com/url-to-json", function(result) {
        latest100 = result;
        checkIfNewPictures(); // I don't know how to do this
        old100 = latest100;
    });
}
setInterval(getNewPictures, 10000);

如你所见,我不知道如何比较old100和latest100。我还认为,如果我可以将X张新图片存储到另一个数组中,这样更新wall的过程就会更容易。

实现这一目标的最实际的方法是什么?

谢谢!

有几种方法可以做到这一点,但这里是我的做法。

您正在处理的数据结构似乎不包含每个图片的唯一标识符。您将需要一种惟一地标识每张图片的方法,因此您必须创建一些东西。

假设您最初像这样输出图像:

$.getJSON("http://bar.com/url-to-json", function(result) {
    $.each(result, function(index, picture) {
        $('.wrapper').append("<img class='json-image' src='" + picture.url + "'/>");
    });
});

您还需要给每个元素一个唯一的标识符,以便它可以被引用。

    ...
    $.each(result, function(index, picture) {
        var pictureID = picture.name + 'something' + picture.location;
        pictureID = pictureID.replace(' ','');
        $('wrapper').append("<img class='json-image' src='" + picture.url + "' id='" + pictureID + "'/>");
    });
    ...

下面是一个函数,用于删除不在最新json中的图像。

function removeImages(json) {
    var newImageIDs = [];
    $.each(json, function(index, picture) {
        //make an array of all the new image ID's
        var pictureID = picture.name + 'something' + picture.location;
        pictureID.replace(' ','');
        newImageIDs.push(pictureID);
    });
    $('.json-image').each(function() {
        if ( newImageIDs.indexOf($(this).attr('id')) < 0 ) {
            //this image is no longer in the json, remove it
            $(this).remove();           
        }
    });
}

现在,当你得到最新的JSON,你可以添加新的和删除那些不再存在。

$.getJSON("http://bar.com/url-to-json", function (result) {
    $.each(result, function (index, picture) {
        var pictureID = encodeURIComponent(picture.name + 'something' + picture.location);
        //only add new images
        if ( !$('#' + pictureID).length ) {
            $('.wrapper').append("<img class='json-image' src='" + picture.url + "' id='" + pictureID + "'/>");
        } 
    });
    removeImages(result);
});