0

我有一种情况,我需要处理一个可能有问题的 CGI 解释器。在所有情况下,我都需要从getJSON呼叫中获得某种类型的回调。这包括发送到testIt函数的虚假参数(见下文)和 CGI​​ 发送虚假响应。我认为将整个事情包装在 try/catch 中以处理第一种情况并添加 .done 来处理第二种情况就可以完成这项工作。但是如果 CGI 处理器输出无效响应,我的 .done 不会被调用。我怎样才能确保我总是收到回电?

我正在使用的代码如下。

function testIt() {
    try
    {
        console.log('start');
        $.getJSON(
            // URL of the server
            cgi_url,
            // pass the data
            {
                data: 'bogus',
            },
            // If the AJAX call was successful
            function() {
                console.log('worked');
            }
        )
        .done(function() {
                console.log('done');
            });
    }
    catch (err) {
        console.log('exception');
    }
}
4

1 回答 1

3

我怎样才能确保我总是收到回电?

用于.always()附加您的处理程序!如果您想以不同的方式处理错误,请使用fail处理程序

console.log('start');
$.getJSON(cgi_url, {data: 'bogus'})
    .done(function() { // If the AJAX call was successful
        console.log('worked');
    })
    .fail(function() { // If the AJAX call encountered an error
        console.log('exception');
    })
    .always(function() { // When the AJAX call ended
        console.log('done');
    });
于 2013-09-10T21:48:17.760 回答