【问题标题】:How do I catch JSON parse errors with JQuery JSON calls?如何使用 JQuery JSON 调用捕获 JSON 解析错误?
【发布时间】:2010-03-08 19:06:50
【问题描述】:

我正在对有时返回无法解析的 JSON 的服务器进行 AJAX 调用。服务器不在我的控制之下,所以我无法修复它。

function eventFunction(evt) {
    $('div#status_bar').show();
    $.ajax({
        url: 'http://buggyserver.com/api/',
        type: 'GET',
        data: { 'mode': 'json', 'q': 'get/data' },
        dataType: 'json',
        success: updateForm
    });
}

function updateForm(returned, status) {
    if (status == 'success') {
        //Update the form here
    }
    $('div#status_bar').hide();
}

返回不可解析的 JSON 时,不会调用 updateForm 函数。

我如何在客户端确保updateForm 函数的最后一行被调​​用以隐藏状态栏?我尝试在 AJAX 调用和 updateForm 周围放置 try { } catch {} 子句。

【问题讨论】:

    标签: javascript json jquery


    【解决方案1】:

    你可以这样做:

    function eventFunction(evt) {
        $('div#status_bar').show();
        $.ajax({
            url: 'http://buggyserver.com/api/',
            type: 'GET',
            data: { 'mode': 'json', 'q': 'get/data' },
            dataType: 'json',
            success: updateForm,
            complete: function() { $('div#status_bar').hide(); }
        });
    }
    
    function updateForm(returned) {
       //Update the form here
    }
    

    complete 回调在成功后触发,无论成功与否。

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 2014-11-18
      • 2012-05-14
      • 2017-07-31
      • 2014-02-17
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多