如何使用JQuery JSON调用捕获JSON解析错误?

时间:2021-01-05 20:22:54

I'm making AJAX calls to a server that sometimes return unparseable JSON. The server isn't under my control, so I can't fix that.

我正在对服务器进行AJAX调用,有时会返回不可解析的JSON。服务器不在我的控制之下,所以我无法解决这个问题。

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();
}

When unparseable JSON is returned, the updateForm functions does not get called.

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

How can I, on the client side, ensure that the last line of the updateForm function gets called to hide the status bar when? I've tried putting try { } catch {} clauses around both the AJAX call and the updateForm.

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

1 个解决方案

#1


1  

You could do this:

你可以这样做:

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
}

The complete callback fires after success, whether it was successful or not.

无论成功与否,完成回调都会在成功后触发。

#1


1  

You could do this:

你可以这样做:

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
}

The complete callback fires after success, whether it was successful or not.

无论成功与否,完成回调都会在成功后触发。