jQuery override $.post function

こ雲淡風輕ζ 提交于 2019-12-20 01:38:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!