Alright, I’ve got an interesting issue. My page makes a JSON request every once in a while. If the data hasn’t changed, it doesn’t need to do anything. The problem is, I can’t figure out a way to prove if it has changed or not.
I tried something like this to no avail:
var stations = null;
function parseDynamicData(ard) {
//this was something that gave me problems for days
//nice little hack to fix it
if (ard['details']['enabled'] == 'true' && ard['song']['art'] != 'undefined');
{
//turns off the 'server offline' page
if (document.location.toString().indexOf('#offline') != -1)
document.location = '/#tracks';
//update UI
$('#track-title').html(htmlDecode(ard['song']['title']));
$('#track-artist').html(htmlDecode(ard['song']['artist']));
$('#track-album').html(htmlDecode(ard['song']['album']));
$('#track-art').attr('src', htmlDecode(ard['song']['art']));
//set if it's play or pause visible
if (htmlDecode(ard['details']['playing']) == 'true') {
$('#control-pauseplay').html('Pause');
$('#control-pauseplay').attr('href', '/track?proc=2');
} else {
$('#control-pauseplay').html('Play');
$('#control-pauseplay').attr('href', '/track?proc=3');
}
//Now update all of the stations
if (stations == null || stations != ard['stations']) {
$.each(ard['stations'], function (key, value) {
alert(key);
});
stations = ard['stations'];
}
}
}
Here is what a normal JSON response looks like:
{
"song": {
"art": "http://cont-sjl-1.pandora.com/images/public/amz/6/2/3/3/886978533326_500W_500H.jpg",
"title": "Hold It Against Me",
"artist": "Britney Spears",
"album": "Femme Fatale Deluxe"
},
"details": {
"playing": "true",
"enabled": "true"
},
"stations": {
"undefined": "False",
"Alex Clare Radio": "False",
"Rap Strength Training Radio": "False",
"Drops Of Jupiter Radio": "False",
"Tween Radio": "False",
"Today's Hits Radio": "True"
}
}
No matter what I do, however, it still goes through the JSON making an alert for every key. Does anybody know what I should do?
I suspect that
stationsandard['stations']are different objects that are identical in structure. If you are rebuildingardafter each JSON request whilestationsholds the array from the previousard, then the two objects are not the same object, so an exact match will fail, regardless whether the objects have identical key-value pairs.What I would do is keep a exact string copy of the last JSON message and compare it with the current JSON string message before you parse it. Otherwise, you’ll need to compare every single key-value pair of the current object against the prospective new one — and if some of those values are objects themselves, things could get a little (needlessly) hairy.
If you can be certain that the server will always stringify a given object O the same way (and assming you don’t need to worry about checking if an object on the client has mutated), then you can simply compare the JSON string versions of the object from the server.