【问题标题】:Run a ajax function to check a json response every 3 seconds运行 ajax 函数以每 3 秒检查一次 json 响应
【发布时间】:2013-10-25 08:25:41
【问题描述】:

我想检查我的用户是否使用 javascript 从另一个系统更新。

我需要帮助编写一个检查 json 响应的函数。是真是假。

url /user/updatecheck/ 有这样的 json 响应:{"updated": "true"}{"updated": "false"}

<script type="text/javascript">

$(document).ready(function() {
    var updated='2013-01-02T10:30:00.000123+02: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/user/updatecheck/返回true,页面不会重新加载。

【问题讨论】:

  • 每半秒检查一次可能是多余的。
  • 也许你应该使用保持活动请求。
  • @EdsonMedina:关于我如何使用 keep alive 的任何提示?

标签: javascript ajax


【解决方案1】:

您调用 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 请求中收到的数据是通过您的成功回调函数的 data 参数返回的,因此您可以使用它。尝试将数据结果打印到控制台(即console.log(data);)或警告它(即alert(data);)。例如,您可能需要调用 data.updated。我不确定您在 if 条件中使用的 json 变量是否已初始化。

【讨论】:

  • 是的。这在我删除 data: dataString 并将 json.updated 更改为 updated 后有效
  • @Garreth00 您可以使用计数器并仅检查特定次数,例如 stackoverflow.com/questions/2956966/… 。或者您可以使用 Date 变量并检查特定的时间量。
猜你喜欢
  • 1970-01-01
  • 2012-01-09
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多