简体   繁体   中英

How do I catch JSON parse errors with JQuery JSON calls?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM