好了,我有一个有趣的问题。我的页面每隔一段时间就发出一个JSON请求。如果数据没有改变,它不需要做任何事情。问题是,我想不出一种方法来证明它是否改变了。
我尝试了这样的东西,但没有用:
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'];
}
}
}
下面是一个普通的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为每个键发出警报。有人知道我该怎么做吗?
发布于 2012-06-11 14:39:30
我怀疑stations
和ard['stations']
是结构相同的不同对象。如果在每次JSON请求之后重新构建ard
,而stations
保存来自前一个ard
的数组,那么这两个对象就不是同一个对象,因此精确匹配将失败,无论这两个对象是否具有相同的键值对。
我要做的是保留最后一条JSON消息的准确字符串副本,并在解析它之前将其与当前的JSON字符串消息进行比较。否则,您将需要将当前对象的每个单独的键值对与预期的新1进行比较,如果其中一些值是对象本身,事情可能会变得有点混乱(不必要)。
如果您可以确定服务器将始终以相同的方式将给定对象O串化(并且确保您不需要担心检查客户端上的对象是否发生了变化),那么您可以简单地比较来自服务器的对象的JSON字符串版本。
发布于 2012-06-11 14:30:46
您可以尝试使用JSON.Stringify吗?显然,您从JSON请求中得到的是JSON,我假设您已经将最后一个请求转换为实际的对象。所以只要打个电话:
JSON.Stringify(Object) === JSONresult
并比较这两个字符串。
https://stackoverflow.com/questions/10981864
复制相似问题