AJAX - 如果JSON已更改,则重新加载页面

时间:2016-05-28 19:41:36

标签: javascript json ajax

我找不到合适的方法来实现这个目标:

我有这个脚本

<script type="text/javascript">
function updateSpots() {

    $.ajax({
        url : '/epark/api/spots/last',
        dataType : 'text',
        success : function(data) {

            var json = $.parseJSON(data);
            var currentMessage = json.dateTime;
            var idPosto = json.idPosto;
            console.log('current '+currentMessage);
            console.log('old '+oldMessage);
            if(currentMessage != oldMessage){

                setTimeout(function(){location.reload();}, 5000);

                $('#idPosto').toggle("higlight");
            }
            oldMessage = currentMessage;    

        }
    });

}

var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";

</script>

如果JSON上的dateTime已更改,则应每3秒检查一次。

问题是我无法迈出第一步。我的意思是,当页面加载时,oldMessage为空,因此if条件不满足。如果我可以“跳”到第一次迭代,那么一切都会顺利进行......

1 个答案:

答案 0 :(得分:1)

var oldMessage = false;

//...

if (oldMessage && oldMessage !== currentMessage) {

//...
相关问题