2012-08-10 25 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'); 
      } 

     } 


    }); 

}