使用jQuery自动刷新div - setTimeout或其他方法? [英] Auto-refreshing div with jQuery - setTimeout or another method?

查看:788
本文介绍了使用jQuery自动刷新div - setTimeout或其他方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你究竟如何使用JavaScript(特别是jQuery)自动刷新 div

How exactly do you make an auto-refreshing div with JavaScript (specifically, jQuery)?

I知道 setTimeout 方法,但这真的是一个好习惯吗?有更好的方法吗?

I know about the setTimeout method, but is it really a good practice ? Is there a better method?

function update() {
    $.get("response.php", function(data) {
        $("#some_div").html(data);
    });
    window.setTimeout("update();", 10000);
}


推荐答案

另一个修改:

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

与此不同的是,它在ajax呼叫为1之后等待10秒。所以刷新之间的时间实际上是10秒+ ajax调用的长度。这样做的好处是,如果您的服务器响应时间超过10秒,则不会发生两个(最终是很多)同时发生的AJAX调用。

The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.

此外,如果服务器无法响应,它将不会继续尝试。

Also, if the server fails to respond, it won't keep trying.

我过去使用类似的方法使用.ajax来处理更复杂的行为:

I've used a similar method in the past using .ajax to handle even more complex behaviour:

function update() {
  $("#notice_div").html('Loading..'); 
  $.ajax({
    type: 'GET',
    url: 'response.php',
    timeout: 2000,
    success: function(data) {
      $("#some_div").html(data);
      $("#notice_div").html(''); 
      window.setTimeout(update, 10000);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
}

这显示加载消息加载(在那里放置一个典型的web 2.0样式的动画gif。)如果服务器超时(在这种情况下需要超过2秒)或任何其他类型的错误发生,它会显示错误,并等待60秒再次联系服务器之前。

This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.

这对于使用大量用户进行快速更新尤其有用,在这种情况下,您不希望每个人都突然瘫痪服务器落后请求只是ti无论如何都要出去。

This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.

这篇关于使用jQuery自动刷新div - setTimeout或其他方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆