Extending Jquery Ajax Success Globally
I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure,
Solution 1:
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaultssuccess: function(data){ //hijack the success handlerif(check(data)){ //checkscallback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaultsreturn $.ajax(options); //send request
}
so your call, instead of $.ajax
, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
Solution 2:
This solution transparently adds a custom success handler to every $.ajax()
call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return_oldAjax(options);
};
})();
Solution 3:
Here's a couple suggestions:
varMADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
functionajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
functionajaxSuccess(data) {
console.log(data);
}
functionajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
// // setup with ajaxSuccess() and call ajax as usual//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------// or// ----------------------------------------------------// // declare the handler right in your ajax call//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});
Working: http://jsfiddle.net/pF5cb/3/
Solution 4:
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
Solution 5:
this is your call to ajax method
functiongetData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});
Post a Comment for "Extending Jquery Ajax Success Globally"