javascript - 函数运行一次成功然后连续失败

标签 javascript jquery json

我不确定为什么我的函数只能正常运行一次。基本上在我的 JSON 中,GhStatus 和 CsStatus 的值均为 0,因此我预计警报会发出两次“崩溃”消息。

但是,这组警报仅发生一次。然后根据 Chrome 开发者工具,我每 2 秒就会收到错误消息:

    Uncaught SyntaxError: Unexpected identifier

但是,输出并未指出代码中发生这种情况的位置=[

    $(document).ready(GrabGhCsStatus());

    function GrabGhCsStatus() {
    var url = '@Html.Raw(Url.Action("index","GhCs"))';
    window.setInterval(
        $.get(url,function(data) {
            if (data.GhStatus == 0) {                                                  
                $('#GhCsStatus_CS').buttonMarkup({ icon: 'myapp-cs' });            
                alert('crash');
            }
            else {
                $('#GhCsStatus_GH').buttonMarkup({ icon: 'myapp-gh' });         
                alert('running');
            }
            if (data.CsStatus == 0) {                                                 
                $('#GhCsStatus_CS').buttonMarkup({ icon: 'myapp-cs' });     
                alert('crash');
            }
            else {
                $('#GhCsStatus_GH').buttonMarkup({ icon: 'myapp-gh' });     
                alert('running');
            }
        }, "json"), 2000);                                                  

   }

我格式化此代码的方式或我放置函数的位置是否会影响输出?

最佳答案

语法错误,添加更多函数并正确关闭它们:

$(document).ready(function() { // needs anonymous function
    GrabGhCsStatus();
});

function GrabGhCsStatus() {
    var url = '@Html.Raw(Url.Action("index","GhCs"))';
    $.get(url, function (data) {
        if (data.GhStatus === 0 || data.CsStatus === 0) {
            $('#GhCsStatus_CS').buttonMarkup({
                icon: 'myapp-cs'
            });
        }else{
            $('#GhCsStatus_GH').buttonMarkup({
                icon: 'myapp-gh'
            });
        }
        setTimeout(GrabGhCsStatus, 2000);
    }, "json");
}

关于javascript - 函数运行一次成功然后连续失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18774589/

相关文章:

javascript - word导入后括号的意义是什么

json - 如何通过 API 将映射函数与 JSON 对象获取结合使用

ios - swift JSON 错误 : Could not cast value of type '__NSDictionaryM' to 'NSArray'

javascript - 创建 CSS 网格

javascript - 使用 CommonJS 进行 Rollup,使用 Treeshaking 进行导入和导出

jquery - 如何将CSS应用于数据表滚动条

jquery - 在页面在 jquery mobile 中完全加载之前不要隐藏加载程序

javascript - setInterval启动我的页面在生成30+数据时就卡顿了

javascript - Angular 链接函数中作用域变量的范围是多少?

php - 带有 jQ​​uery 的 Ajax 请求不起作用