1

我像这样加载一个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”总是正确的。

帕特里克

4

6 回答 6

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);
于 2012-12-15T13:53:57.750 回答
1

这对我有用:

$(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);
});
于 2017-05-02T13:38:01.600 回答
0

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

var auto_refresh = setInterval(function () {
  $.get('check_change.php', function(data) {
    if (data.changed) {
      $('#nowplaying').load('nowplaying.php').fadeIn("slow");
    }
  });
}, 10000);
于 2012-12-15T13:53:34.310 回答
0

参见 dom 突变事件。然后您将能够检查是否更改了某些内容。https://developer.mozilla.org/en-US/docs/DOM/Mutation_events

于 2012-12-15T13:54:05.810 回答
0

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

于 2012-12-15T13:56:24.470 回答
0

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

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);
于 2012-12-15T21:55:30.953 回答