javascript - Detect how many elements have changed in JSON array with jQuery -
i'm new web development, may seem trivial you:
i'm building wall displays mosaic of 100 miniatures of landscape pictures. urls of these pictures remote json contains 100 latest uploaded pictures, starting recent. json updated.
json construction :
[ { "name": "blue mountains", "url": "http://foo.com/url-to-picture", // <- recent "location": "canada" }, { "name": "yellow lake", "url": "http://foo.com/url-to-picture", // <- sec recent "location": "greece" }, ... ] i'd check json every 10 seconds , observe if new pictures have been uploaded and, if so, i'd know how many , replace oldest pictures wall new ones.
all come this:
function getnewpictures() { $.getjson("http://bar.com/url-to-json", function(result) { latest100 = result; checkifnewpictures(); // don't know how old100 = latest100; }); } setinterval(getnewpictures, 10000); as can see, have no clue how compare old100 , latest100. suppose it'd easier me if store x new pictures array process of updating wall easier.
what practical way accomplish this?
thanks!
there few ways go it, here how it.
it appears info construction working not contain unique identifier each picture. need way uniquely identify each picture, have create something.
say outputting images this:
$.getjson("http://bar.com/url-to-json", function(result) { $.each(result, function(index, picture) { $('.wrapper').append("<img class='json-image' src='" + picture.url + "'/>"); }); }); you need give each element unique identifier can referred to.
... $.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 + "'/>"); }); ... here function remove images not in latest json.
function removeimages(json) { var newimageids = []; $.each(json, function(index, picture) { //make array of 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 no longer in json, remove $(this).remove(); } }); } now, when latest json can add together new ones , remove ones no longer exist.
$.getjson("http://bar.com/url-to-json", function (result) { $.each(result, function (index, picture) { var pictureid = encodeuricomponent(picture.name + 'something' + picture.location); //only add together new images if ( !$('#' + pictureid).length ) { $('.wrapper').append("<img class='json-image' src='" + picture.url + "' id='" + pictureid + "'/>"); } }); removeimages(result); }); javascript jquery arrays json comparison
No comments:
Post a Comment