除了向每个回调添加 try..catch 块之外,还有什么方法可以处理 jQuery 中 AJAX 回调引发的异常吗?在这种情况下不会调用错误函数。
$.ajax(
{
url: 'myurl.rails',
success: function( data )
{
throw 'Oh no!';
},
error: function ( xhr, textStatus, errorThrown )
{
console.log( 'AJAX call failed', xhr, textStatus, errorThrown );
}
} );
如果您查看 jQuery 1.4.2 的非缩小版本,相关行是 5264 到 5274:
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [xhr, s] );
}
}
jQuery 只是调用success
函数应用于设置对象(如果存在),而不关心函数返回或抛出什么。
你可以做的是使用jQuery.ajaxSetup() http://api.jquery.com/jQuery.ajaxSetup/像这样:
jQuery.ajaxSetup({
success: function() {
try {
if ( this.mysuccess ) {
this.mysuccess.apply( this, arguments );
}
}
catch(err) {
// whatever
}
}
});
And use mysuccess
(或者任何你喜欢的称呼)而不是success
在个人jQuery.ajax
calls.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)