2013-04-10 32 views
1

我使用ajax來檢查是否沒有新的警報存儲在我的sql數據庫中。我已經將它設置爲每30秒運行一次,但它不斷調用每秒鐘檢查數據庫的函數。這是我的代碼。ajax調用不斷運行

這是視圖中的代碼。 「_Tasks」是我的局部視圖,它將成爲即將更新的視圖。我沒有做過任何成功的回報,因爲它從來沒有達到那個代碼。

@Html.Action("_Tasks") 
      <script type="text/javascript"> 
       (function poll() { 

        $.ajax({      
         type: 'GET', 
         cache: false, 
         url: '@Url.Action("TasksRefresh")', 
         dataType: "json", 
         complete: poll, 
         timeout: 30000, 
         success: function (data) { 
          if (data.success == true) 
           alert("Hello"); 

         } 
        }); 
       })(); 
     </script> 

這是在控制器

public JsonResult TasksRefresh() 
     { 
      var alerts = getAlerts(); 
      var cache = HttpRuntime.Cache["Tasks"]; 
      if (cache == alerts) 
      { 
       return Json(new 
           { 
            success = false, 
           }); 
      } 
      else 
      { 
       return Json(new 
       { 
        success = true, 
        // View = this.Re 
       }); 
      } 

     } 

回答

3

試試這個:

(function poll() { 
    $.ajax({      
    type: 'GET', 
    cache: false, 
    url: '@Url.Action("TasksRefresh")', 
    dataType: "json", 
    complete: function() { setTimeout(poll, 30000); }, // Changed, call poll again when 30s has pasted 
    timeout: 30000, // This just says it fails if the request takes more than 30s 
    success: function (data) { 
     if (data.success == true) 
     alert("Hello"); 

    } 
    }); 
})(); 
+0

謝謝,這工作。 – zms6445 2013-04-10 13:33:28

2

超時是不是一個延遲。超時是在考慮請求失敗之前應等待多長時間。通過將complete設置爲poll,您告訴它立即撥打另一個電話。你需要延遲你的complete函數。

1

我可以猜測是,你在完成Ajax調用的再次執行該查詢功能。這可能需要一秒鐘才能完成該Ajax調用。
您可以在JavaScript代碼中使用計時器。嘗試使用settimeoutsetInterval。並在該計時器中進行ajax調用。看看是否有幫助。

0

timeout: 30000只是爲了確保您的ajax調用將等待最長的響應時間。

一旦ajax調用完成,您正在執行輪詢函數,這就是爲什麼調用如此快速的原因。