如何使页面自动更新像facebook一样,不使用setTimeout()或setInterval()


How to make page auto-update like facebook does, without using setTimeout() or setInterval()

是否可以不使用setInterval()setTimeout() ?如何像Facebook一样更新页面?

如果我在浏览器中打开Facebook,当其他朋友添加任何新帖子时,页面会自动更新。我怎样才能做到这一点呢?当我使用setInterval()setTimeout()时,页面变得很重。提前谢谢。

setInterval(ajaxCall1, 3000);
function ajaxcall1 {
    $.ajax({
        url: 'echo_file.php', 
        datatype: 'json',
        success: function(data) {
            seriesOptions = data;
            createChart();
        },
    });

使用web套接字将数据推送到客户端是AJAX轮询的更好解决方案。

这允许服务器注意到何时发生更改,并主动将数据推送到相关的客户端。这样就消除了每隔几秒钟发送重复请求所造成的服务器和客户端不必要的负载。

一个流行的web套接字解决方案是NodeJs和socket IO的结合。这些资源的链接可以在这里找到:

http://nodejs.org/
http://socket.io/

这些相对容易掌握,您可以在几分钟内开始使用。

Try This

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>
    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }
    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",
            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */
            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };
    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>
详细