0

我想检查我的用户是否使用 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,页面不会重新加载。

4

1 回答 1

0

作为 setInterval 的一部分调用 jQuery ajax 函数的方式是不正确的。请尝试将它放在一个函数中,

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 变量是否已初始化。

于 2013-10-25T14:54:13.033 回答