仅在更改时刷新

时间:2012-12-15 13:49:04

标签: jquery load

我加载了这样的div:

var auto_refresh = setInterval(
function ()
{
    $('#nowplaying').load('nowplaying.php').fadeIn("slow");
}, 10000);

我只想在页面发生变化时加载。 我怎么能用“改变”来做到这一点?

这是我尝试过的:

function ()
{
    var cachedDOM = $('div#nowplaying').html();
    $.get('nowplaying.php',function(data){
        if (cachedDOM != data) {
        $('#nowplaying').load('nowplaying.php').fadeIn("slow");
        }
    }
    )
}, 3000);

问题是“cachedDOM!= data”始终为真。

帕特里克

6 个答案:

答案 0 :(得分:1)

我想你的意思是在body中改变了一些东西。你可以这样做:

var cachedDOM = $('body').html();
var auto_refresh = setInterval(
function ()
{
    if(cachedDOM != $('body').html()) 
       $('#nowplaying').load('nowplaying.php',function(){cachedDOM = $('body').html();}).fadeIn("slow");
}, 10000);

答案 1 :(得分:0)

所以你需要另一个页面让你知道它是否会改变。

var auto_refresh = setInterval(function () {
  $.get('check_change.php', function(data) {
    if (data.changed) {
      $('#nowplaying').load('nowplaying.php').fadeIn("slow");
    }
  });
}, 10000);

答案 2 :(得分:0)

参见dom变异事件。然后你就可以检查是否有变化。 https://developer.mozilla.org/en-US/docs/DOM/Mutation_events

答案 3 :(得分:0)

而不是使用load,您可以使用ajax请求并将ifModified - 标记设置为true。这只会在页面内容发生变化时为您提供定义的响应。服务器端(etag)可能需要更多设置才能使其正常工作。 这是指向文档的链接:jquery ajax call

答案 4 :(得分:0)

谢谢xdazz。 这就是我所做的:

var auto_refresh = setInterval(
function ()
{
function getcursong(){  
 var result = null;
 var scriptUrl = "get_current_song.php";
 $.ajax({
    url: scriptUrl,
    type: 'get',
    dataType: 'html',
    async: false,
    success: function(data) {
        result = data;
    } 
 });
 return result;
}    
gcs = getcursong();
okas = $('#song').html();
if (gcs != okas){
    $('#nowplaying').load('nowplaying.php').fadeIn("slow");
}
}, 10000);

答案 5 :(得分:0)

这对我有用:

$(document).ready(function() {
    function loadData() {
        $('#nowplaying').load('currentsong.php').fadeIn("slow");
    }

    var result = null;

    function checkdata() {
        var scriptUrl = "currentsong.php";
        $.ajax({
            url: scriptUrl,
            type: 'get',
            dataType: 'html',
            async: true,
            cache: false,
            success: function(data) {
                if (result != data) {
                    result = data;
                    loadData();
                };
            }
        });
    }

    var auto_refresh = setInterval(function() {
        checkdata();
    }, 4000);
});