2010-03-08 47 views
0

我正在对有时返回无法解析的JSON的服务器进行AJAX调用。服务器不在我的控制之下,所以我无法解决这个问题。如何用JQuery JSON调用捕获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(); 
} 

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

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

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回调火灾,无论是成功还是失败:

回答

1

你能做到这一点。

+0

不错。我喜欢这个主意。 – Jrgns 2010-03-08 19:16:30