Can I listen to a specific element on ajaxComplete instead of 'document'?

前端 未结 3 1850
闹比i
闹比i 2020-12-12 02:39

Good morning,

I am using the jQuery ajaxComplete Function and I wonder if it would be possible to use it on a specific element (div)?

Example:



        
3条回答
  •  情歌与酒
    2020-12-12 03:22

    While you can't call the unknown form, you can do as I did and create an "Ajax Wrapper" and use a complete handler here which when invoked by the wrapper, will give you ajaxComplete functionality with the desired addition. It has the advantage of condensing code, while not affecting capability. The disadvantage is a small amount of performance overhead.

    Define all the defaults you want within the function. I like this because I use some near-global success/error handles for dialogs.

    function ajaxWrapper(srcForm,overrides) {
      var ret = $.extend(true,{type: "POST",
        url: $(srcForm).attr('action'),
        contentType: "application/x-www-form-urlencoded",
        data: {
            tzOffset: new Date().getTimezoneOffset(),
        },
        success: // success handler,
        error: // error handler,
        beforeSend: function(jqXhr,plainObject) {
            $(srcForm).find("button[type=submit], button[type=reset], input[type=submit], input[type=reset]").prop("disabled", true);
        },
        complete: function(jqXHR, textStatus) {
            $(srcForm).find("button[type=submit], button[type=reset], input[type=submit], input[type=reset]").prop("disabled", false);
        }
      },overrides);
      $.ajax(ret);
    }
    

    It uses $.extend(true,,) to merge the objects. True sends it to a deep copy enabling both objects to have a data object and inheriting properties from both, while overriding in favor of overrides where the two object's data might conflict.

    If you don't want an override, remove true,. False is not supported, as per the current docs.

    I call the function like simple as this

    ajaxWrapper($(this),{url: $(this).attr('action'), // I choose to leave action in just to make clear to me where this ajax is submitting
        data: {ObjectID: $('#myID').val(),
            f1: $('#f1').val(),
            f2: $('#f2').val(),
            someCheckbox: $('#someCheckbox').prop('checked')}
    });
    

提交回复
热议问题