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

时间:2014-07-21 09:36:52

标签: php jquery ajax

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

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

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

2 个答案:

答案 0 :(得分:4)

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

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

流行的Web套接字解决方案是NodeJ和Socket IO的组合。可以在此处找到这些资源的链接:

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

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

答案 1 :(得分:0)

试试这个

<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>

More Details