var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
var xhr = _orgAjax();
DoSomeLogging();
return xhr;
};
我继承了上面的代码。有人可以确认我的理解吗,这将覆盖页面上其他任何位置的任何 $.ajax(...)
调用并每次执行 DoSomeLogging()
?
我正在寻找一个不同的错误,但偶然发现了这个错误,并想确保我理解这段遗留代码的作用?
我不相信这是 xhr
函数的良好实践/使用,但有兴趣听听您的意见。我们使用的是 Jquery 1.7.1。
最后,出于好奇,如果 (async: false
) 调用 _orgAjax()
无法返回,会到达日志记录方法吗?
谢谢。
最佳答案
Can someone confirm my understanding that this will override any $.ajax(...) call anywhere else on the page and execute DoSomeLogging() each time?
是的。这将定义全局默认行为,除非在本地 ajax 实现中被覆盖。
定义全局设置的更有记录的方法是使用 ajaxSetup() 。
但是,您也可以使用 ajaxSettings
设置默认的全局行为,尽管 jQuery 文档中没有直接记录这种特殊的方式。
参见DEMO - 成功
Lastly, out of curiosity, what if _orgAjax() failed to return if an (async: false) call, would the logging method even get reached?
这些设置正在配置 beforeSend
,因此无论 Esailija 正确指出的异步设置如何,都将始终调用日志记录方法。
参见DEMO - 使用async: true
,在返回之前调用日志记录
请参阅DEMO - 使用async: false
,日志记录也会在返回之前调用
但是请注意,根据 ajax documentation :
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is
deprecated; you must use the complete/success/error callbacks.
我知道您正在使用 1.7.1,但如果某些内容被弃用,通常有一个很好的理由,我认为为此做好准备没有任何坏处。
默认情况下,配置 ajax 时完整
登录:
参见DEMO - 配置文档完整
的默认日志记录。
我知道这会让你的日志记录在发送之后而不是之前执行,但我认为这似乎是 1.8 更喜欢的方式。
关于javascript - 确认使用 jQuery.ajaxSettings.xhr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926484/