2013-10-25 74 views
0

我想檢查用戶是否使用javascript從另一個系統更新。運行ajax函數,每3秒檢查一次json響應

我需要編寫一個函數來檢查json響應。如果是真或假。

的URL /user/updatecheck/有這樣的JSON響應:{"updated": "true"}{"updated": "false"}

<script type="text/javascript"> 

$(document).ready(function() { 
    var updated='2013-01-02T10:30:00.00:00'; //user variable from the system, will be empty if the user is not updated  

    if (!updated){ 
     $('#not-updated').modal('show'); 

     var updatedCheck = window.setInterval( 
     $.ajax({ 
        url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"} 
        data: dataString, 
        dataType: "json", 
        success: function(data){ 

         if (json.updated == 'true') { //not sure if this is the correct method 
          window.clearInterval(updatedCheck); 
          //The user is updated - the page needs a reload 
         } 
        } //success 

       }) 
     , 3000); //Hoping this is the function to check the url every 3 seconds until it returns true 
    } 

}); 
$(document).ajaxStop(function(){ 
    window.location.reload(); 
}); 

</script> 

這似乎並沒有工作。不知道我的ajax函數是否正確,如果用戶一開始沒有更新,我只會得到模態窗口,並且如果url返回true,頁面不會重新加載。

+1

檢查半秒可能是矯枉過正。 – Brandon

+0

也許你應該使用保持活着的請求。 –

+0

@EdsonMedina:我如何使用任何提示保持活着? –

回答

0

您將jQuery ajax函數作爲setInterval的一部分調用的方式並不合適。請儘量把它放在一個函數中,

var updatedCheck = window.setInterval( 
     function(){$.ajax({ 
        url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"} 
        data: dataString, 
        dataType: "json", 
        success: function(data){ 

         if (json.updated == 'true') { //not sure if this is the correct method 
          window.clearInterval(updatedCheck); 
          //The user is updated - the page needs a reload 
         } 
        } //success 

       })} 
     , 3000); 

,您將收到來自Ajax請求的數據通過你成功的回調函數的數據參數返回,這樣你就可以使用它。嘗試將數據結果打印到控制檯(即console.log(data);)或提醒它(即alert(data);)。例如,你可能需要調用data.updated。我不確定您在if條件中使用的json變量是否已初始化。

+0

是的。這工作後,我刪除了'data:dataString'並將'json.updated'更改爲'updated' –

+0

@ Garreth00您可以使用計數器並只檢查特定次數的示例,http://stackoverflow.com/questions/2956966/javascript-telling-setinterval-to-only-fire-x-times-of-times。或者您可以使用Date變量並檢查特定的時間量。 – melc