我已经构建了一个web应用程序,它在几十个不同的页面上大量使用jQuery.ajax()函数。当然,每次使用jQuery.ajax()都会传递一个configuration对象,该对象带有一个函数,用作'success‘属性的回调函数。
我现在遇到了这样一种情况:如果服务器为任何给定的ajax请求返回特定的错误代码,我希望在多个页面上全局执行某个操作。我正在考虑以某种方式覆盖jQuery库的一部分,方法是在我的页面头部包含javascript,它将执行条件检查操作,然后继续执行传递到configuration对象中的任何回调函数。这个是可能的吗?我目前正在检查jQuery库的源代码,看看我是否能做到这一点。
发布于 2012-03-09 21:08:11
我认为您需要看看Global Ajax事件处理程序。
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
发布于 2014-04-15 01:56:55
在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
}
});发布于 2015-07-14 03:44:07
我最终使用$.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)
}
}
})https://stackoverflow.com/questions/9634532
复制相似问题