2012-08-10 44 views
0

我有使用jquery ajax的自动请求,我正在使用此功能来检测新的聊天消息&通知情况。有时我在想如果客户端自动请求没有完成有什么影响,使用jquery ajax和自动请求有什么作用?

我担心我的服务器关闭,因为我认为这就像DDOS HTTP节流。

这是我的代码

$(function(){ 
     initChat(); 
    }); 

    /* 
    * initialize chat system 
    */ 
    function initChat() { 
     setTimeout("notifChat()" ,2000);  
    } 

    function notifChat() { 
     $.ajax({ 
      url: '/url', 
      type:"GET", 
      data: {id:$("#id").val()}, 
      success:function (data,msg) { 
       //to do success 

      } 
     }); 
     setTimeout("notifChat()" ,2000); 
    } 

我的问题是

  1. 可以关闭服务器或使服务器挂了?
  2. 如果不是更好的想法任何思维建议?
+0

有很多更好的方法可以使代码更有效率。比如,如果出现错误,请求/网址应该检查以确保它成功并具有最大重试请求 – 2012-08-10 04:10:35

+1

[您可能想知道关于您的问题的所有内容;通常被称为“The Two HTTP Connection Limit Issue”](http://www.openajax.org/runtime/wiki/The_Two_HTTP_Connection_Limit_Issue) – Ohgodwhy 2012-08-10 04:16:05

+0

@RPM你能给我举个例子吗? – viyancs 2012-08-10 06:06:42

回答

1

注意:这不是生产就绪代码,我没有测试过它。

这段代码的一对夫妇weekness:

它不处理的两个HTTP连接限制

优势:

如果服务器返回一个错误(如服务器错误404403402它可以告诉。 ...)

var failed_requests = 0; 
var max = 15; 

$(function(){ 

    initChat(); 
}); 

/* 
* initialize chat system 
*/ 
function initChat() 
{ 
    setTimeout(
      function() 
      { 
       notifChat(); 
      }, 2000) 
} 


function notifChat() { 
    $.ajax({ 
     url: '/url', 
     type:"GET", 
     data: {id:$("#id").val()}, 
     success:function (data,msg) 
     { 
      //to do success 

     }, 
     complete: function() 
     { 

      // either call the function again, or do whatever else you want. 


     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) 
     { 
      failed_requests = failed_requests + 1; 

      if(failed_requests < max) 
      { 
       setTimeout(
         function() 
         { 
          notifChat(); 
         }, 2000) 
      } 
      else 
      { 
       alert('We messed up'); 
      } 

     } 


    }); 

}