2013-10-25 76 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