我如何检查实时更新,而无需使用的setInterval /超时? [英] How can I check for live updates without using setInterval/timeout?

查看:405
本文介绍了我如何检查实时更新,而无需使用的setInterval /超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建立一个社交网络,我试图获取实时通知。目前,该网站发送一个Ajax请求使用的setInterval每隔几秒钟。它看起来是这样的:

Building a social network, I'm trying to fetch live notifications. Currently, the site sends an AJAX request every few seconds using setInterval. It looks something like this:

setInterval ( function(){
    url = base_dir+"/ajax/file.php";
    data = "data=someData";
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function(x) {
            if(x && x.overrideMimeType) {
                x.overrideMimeType("application/json;charset=UTF-8");
            }
        },
        success: function(JSON){
            // retrieve data here   
        }
    });
}, 5000);

这完美的作品,但我很担心,在创建服务器过载。我尝试了彗星的技术,但由于某种原因,它发出比上面的code多的请求。 是否有推动这一数据的住任何其他更实用的技术?

That works perfectly, but I'm very worried about that creating servers overload. I tried the comet technique but for some reason it sends much more requests than the above code. Is there any other more useful technique for pushing this data live?

编辑: 为了实现长轮询我用这里提到的以下(使用的示例:的http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery):

For implementing long polling I used the following (used the example mentioned here: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery):

(function poll(){
    url = base_dir+"/ajax/file.php";
    data = "data=someData";
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function(x) {
            if(x && x.overrideMimeType) {
                x.overrideMimeType("application/json;charset=UTF-8");
            }
        },
        success: function(JSON){
            // retrieve data here   
        },
complete: poll,
timeout: 5000
    });
})();

还有一个可能性,我可能不会得到彗星原则正确的。

There's a possibility that I might not get the comet principle right.

PHP code:

// Checks for new notifications, and updates the title and notifications bar if there are any
 private static function NotificationsCounter (){
    //self::$it_user_id                                     = query that retrieves my id for further checks;                                                        
    //$friend_requests_count                                = query that retrieves the friend requests count;
    //$updates_count                                        = query that retrieves the updates count;               
    $total_notifications                                    = $friend_requests_count+$updates_count;

    if ($total_notifications > 0) $addToTitle = "(".$total_notifications.")";
    else $addToTitle = "";

    if ($updates_count > 0) $counterHTML = "<span class='notification_counter' id='updates_counter' style='float: right;'>".$updates_count."</span>";
    else $counterHTML = "";

    $data = array("counter"=>$total_notifications,"addToTitle"=>$addToTitle,"counterHTML"=>$counterHTML,);
    echo json_encode($data); // parse to json and print
}

由于Facebook的使用PHP为好,他们怎么办呢?

Since Facebook uses PHP as well, how do they do it?

推荐答案

您应该使用的WebSockets 。您可以连接到服务器并注册的onMessage处理。每当服务器有什么形式发送到客户端,你的处理程序将被调用。没有超时需要。

You should use websockets. You can connect to the server and register onmessage handler. Whenever the server has anything to be send to client, your handler will get invoked. No timeout needed.

为您在您的浏览器的WebSocket支持。截至目前,只有浏览器,Opera和Safari浏览器支持他们。

Check for websocket support in your browser. As of now, only Chrome, Opera and Safari support them.

if ('WebSocket' in window){
   /* WebSocket is supported. You can proceed with your code*/
} else {
   /*WebSockets are not supported. Try a fallback method like long-polling etc*/
}

连接

var connection = new WebSocket('ws://example.org:12345/myapp');

处理程序

connection.onopen = function(){
   console.log('Connection open!');
}

connection.onclose = function(){
   console.log('Connection closed');
}

connection.onmessage = function(e){
   var server_message = e.data;
   console.log(server_message);
}

文件:<一href="http://www.developerfusion.com/article/143158/an-introduction-to-websockets/">http://www.developerfusion.com/article/143158/an-introduction-to-websockets/

这篇关于我如何检查实时更新,而无需使用的setInterval /超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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