[英]Intercept jQuery.ajax's 'success' callback function before execution
我建立了一个Web应用程序,该应用程序在数十个不同的页面上大量使用了jQuery.ajax()函数。 自然地,每次使用jQuery.ajax()都会向配置对象传递一个函数,该函数用作“ success”属性的回调。
我现在遇到一种情况,如果服务器为任何给定的ajax请求返回某个错误代码,我想在多个页面上全局执行某种操作。 我正在考虑通过在页面的页眉中包含javascript来覆盖jQuery库的一部分,这将执行条件检查操作,然后继续执行在配置对象中传递的任何回调函数。 这可能吗? 我目前正在查看jQuery库的源代码,以查看是否可以执行此操作。
在jQuery 1.5+中,您可以通过$.ajax
的converters
选项实现此目的。 通常,转换器只应该转换从Web服务器接收的数据,并将其传递给成功回调,但是如果需要,您可以在其中运行其他代码。
将此代码放入嵌入在您所有页面中的js文件中。
$.ajaxSetup({
// the converter option is a list of dataType-to-dataType conversion functions
// example: converters['text json'] is a function that accepts text and returns an object
// note: to redefine any single converter, you must redefine all of them
converters: {
"text json": function (text) {
// NOTE: this converter must return a parsed version of the json
var result = jQuery.parseJSON(text);
if (result.errorMessage) {
// catch the error message and alert
alert(result.errorMessage)
}
return result;
},
"text html": true,
"* text": window.String,
"text xml": jQuery.parseXML
}
});
完整示例: http : //jsfiddle.net/waltbosz/8a8fZ/
我认为您需要查看Global Ajax事件处理程序。
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
我最终使用$.ajaxSetup
以全局方式覆盖成功回调,如下所示:
$.ajaxSetup({
beforeSend: function(xhr, options) {
var originalSuccess = options.success
options.success = function(data, textStatus, jqXhr) {
// trigger some sort of event here for interested listeners
originalSuccess.apply(this, arguments)
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.