2009-12-06 101 views
0

在我的代碼中,我需要每隔5秒使用ajax輪詢一次url。 URL返回一個json響應。以下是我在$(document).ready內部編寫的代碼來執行此操作。但是,setTimeout()函數不起作用。在收到響應後立即調用startPoll()函數。我希望在接收到響應之後停止5秒鐘,然後再次調用startPoll函數。有任何解決這個問題的方法嗎 ?使用jquery在基於ajax的輪詢中使用setTimeout問題

$(document).ready(function(){ 


    var startPoll = function() { 
     $.post('<url>', {},onPollRequestComplete, 'json'); 

    } 

    var onPollRequestComplete = function(response) { 

     responseObject = eval(response); 

     if(responseObject.success) { 
      //Do something here 
     } 

     setTimeout(startPoll(),5000); /*Make next polling request after 5 seconds*/   

} 

startPoll(); 

}); 

謝謝

回答

5

這是你的問題:

setTimeout(startPoll(),5000); 

你立即調用startPoll,不5秒後。相反,你應該通過了所有的功能,像這樣:

setTimeout(startPoll,5000); 

如果你想在輪詢每5秒觸發即使以前的調查沒有工作(遇到服務器錯誤),你應該使用setInterval代替。如果您希望能夠在發生錯誤時停止輪詢,現在的代碼非常棒。

+0

感謝Magnar,修復它!:) – johnswr 2009-12-06 12:01:45

1

我想,而不是setTimeout的,你需要使用的setInterval

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      var startPoll = function() { 
       $.post('url', {}, function(response) { 
        var responseObject = eval(response); 

        if (responseObject.success) { 
         alert('hi'); 
        } 
       }, 'json'); 
      } 

      setInterval(startPoll, 5000); /*Make next polling request after 5 seconds*/ 

     }); 
    </script> 
</head> 
<body> 
</body> 
</html> 
+0

感謝您的回覆Phil.setInterval沒有工作:( – johnswr 2009-12-06 11:40:20

+0

我認爲這是你的代碼,我已經把一個編輯的版本,現在適用於我的作品 – Phil 2009-12-06 11:44:02