如何在不使用setInterval/timeout的情况下检查实时更新?

tal*_*of9 9 javascript ajax comet

建立一个社交网络,我正在尝试获取实时通知.目前,该站点使用setInterval每隔几秒发送一次AJAX请求.它看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

这完全有效,但我非常担心创建服务器过载.我尝试了彗星技术但由于某种原因它发送的请求比上面的代码多得多.有没有其他更有用的技术来推送这些数据?

编辑:为了实现长轮询我使用了以下(使用此处提到的示例: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
    });
})();
Run Code Online (Sandbox Code Playgroud)

有可能我没有得到正确的彗星原理.

PHP代码:

// 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
}
Run Code Online (Sandbox Code Playgroud)

由于Facebook也使用PHP,他们是如何做到的?

ATO*_*TOA 7

你应该使用websockets.您可以连接到服务器并注册onmessage处理程序.只要服务器有任何要发送给客户端的内容,就会调用您的处理程序.不需要超时.

在浏览器中检查websocket支持.截至目前,只有Chrome,Opera和Safari支持它们.

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*/
}
Run Code Online (Sandbox Code Playgroud)

var connection = new WebSocket('ws://example.org:12345/myapp');
Run Code Online (Sandbox Code Playgroud)

处理程序

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);
}
Run Code Online (Sandbox Code Playgroud)

文档:http://www.developerfusion.com/article/143158/an-introduction-to-websockets/

  • 仅供参考,IE10也支持websocket (2认同)