问题
First of all I apologize for my poor english... Hope someone will understand my question and help me...
I'm working on a project using lots of $.post call and I want to improve them by adding the same verification for all of them.
I do not want to change all scripts one by one so is there any way to override the $.post function to add the same thing to all of them at the same time ? Or maybe a way to trigger another function on each $.post ? Something like :
$.post.each(function(){[...]});
or
$('body').on('post', function(){[...]});
Thanks !
EDIT : Finally did it as I wanted ! Here is my code :
// Override $.post
(function(){
// Store a reference to the original remove method.
var originalPostMethod = jQuery.post;
// Define overriding method.
jQuery.post = function(data){
// Execute the original method.
var callMethod = originalPostMethod.apply( this, arguments);
callMethod.success(function(){
//console.log('success');
});
callMethod.error(function(){
//console.log('error');
});
callMethod.complete(function(){
//console.log('complete');
return callMethod;
});
}
})();
回答1:
$.post = function() {
var _method = $.post;
// do something you want
console.log("do someting");
return _method.apply($, Array.prototype.slice.apply(arguments));
}
回答2:
You can create a jQuery-Plug which does the validation and then posting the data to the Server. The basics can be found in the jQuery tutorial.
来源:https://stackoverflow.com/questions/11930295/jquery-override-post-function