每1秒发送多个ajax请求

时间:2012-02-16 18:14:16

标签: ajax jquery httprequest

我要像Facebook聊天一样聊聊:)

我正在使用

这样的请求

在这里获取房间用户和roomBody

$('.room_users,.room_body').each(function () {
                 var page    = $(this).attr("page");
                 var room_id = $(this).parents('.room').children('.roomy_id').attr("value") ;
                 var url     = page+room_id ;
                 window.setInterval(function () { $(this).load(url);}, 200);
         });

Here To Get Room Lists

         $('#room_list').each(function () {
                 var page = $(this).attr("page");
                  var url = page ;
                  window.setInterval(function () {
                      $(this).load(url);
                  }, 60000);
         });

如您所见,我的请求每1秒发送一次,但并非所有请求都返回202状态

很多时候它返回404 notfound

有些时间请求每1秒发送两次

Here is pic of this

2 个答案:

答案 0 :(得分:1)

如果您的服务器支持websockets或任何形式的Comet,如长轮询,请尝试使用一个。同时,为您的请求添加超时,并仅在上一次返回或超时后发送下一个ajax请求...

function updaterooms() {
  $.ajax({
    type: "GET",
    url: page,
    async: true,
    cache: false,
    timeout:5000,
    success: function(data){
      // do what you need with the returned data...
      setTimeout('updaterooms()',1000);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
      $("#error").text("ERROR: " + textStatus + " (" + errorThrown + ")");
      setTimeout('updaterooms()',1000);
    }
  });
}

答案 1 :(得分:0)

不应每秒都向请求服务器发送垃圾邮件,而应该查看Comet

这是一种模式,它使用一个长时间运行的请求在短时间内将数据流式传输到浏览器很长一段时间。

相关问题