好吧,我有一个有趣的问题。我的页面每隔一段时间就会发出一个 JSON 请求。如果数据没有改变,则不需要执行任何操作。问题是,我想不出办法来证明它是否改变了。
我尝试过类似的方法,但没有成功:
var station = 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'];
}
}
}
正常的 JSON 响应如下所示:
{
"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"
}
}
但是,无论我做什么,它仍然会通过 JSON 为每个键发出警报。有人知道我应该做什么吗?
最佳答案
我怀疑stations
和ard['stations']
是结构相同的不同对象。如果您正在重建ard
每次 JSON 请求之后 stations
保存前一个数组 ard
,那么这两个对象不是同一个对象,因此无论对象是否具有相同的键值对,精确匹配都会失败。
我要做的就是保留最后一个 JSON 消息的精确字符串副本,并在解析之前将其与当前的 JSON 字符串消息进行比较。否则,您需要将当前对象的每一个键值对与预期的新对象进行比较——如果其中一些值本身就是对象,事情可能会变得有点(不必要)麻烦。
如果您可以确定服务器始终会以相同的方式对给定对象进行字符串化O(并且您无需担心检查客户端上的对象 已变异),那么您可以简单地比较来自服务器的对象的 JSON 字符串版本。
关于javascript - 运行前判断数据是否是新的(比较数组和JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10981864/