Better way to temporarily disable ajax submission on ajaxForm plugin

蹲街弑〆低调 提交于 2020-01-04 05:18:35

问题


I'm using the jQuery malsup ajaxForm plugin on a form. I've got a bunch of POST vars that get submitted and this is working fine, I want to use the same post vars to perform an Export to file option. This means using the same form for both submission types.

Because you can't download Files through an AJAX submission, I'm using .unbind('submit').submit() on the form to prevent the previously assigned ajax event handlers from firing.

After this unbinding occurs, I then have to re-run the ajaxForm constructor when the user wants to change the filters using AJAX (not for the export).

Before I invest more time in fixing the edge cases and a couple of bugs, I wondered if there was a cleaner way to do this?


回答1:


Use custom events and trigger()!

First, put a radio button on your form to allow the user to switch between AJAX/Export to file. Let's say the name of this field is submitAction

Second, your submit listener acts only to decide what happens next based upon the value of the submitAction radio. This is where you fire the custom events (we define them in step 3):

$('form.specialform').on('submit',function(e){
    e.preventDefault();
    var checked = $(this).closest('[name="submitAction"]').filter(':checked');
    if(checked.val() == 'ajax'){ //ajax!
        $(this).trigger('submitAJAX');
    } else { //export to file!
        $(this).trigger('submitExport');
    }
});

Third, define your custom events with two event listeners:

$('form.specialform').on('submitAJAX',function(e){
    //do AJAX call here
});

$('form.specialform').on('submitExport',function(e){
    //do file export here
});

As you can see, doing it this way allows you to avoid the mess of unbinding and rebinding the same event handlers a bunch of times.

Does that help?




回答2:


Thanks a lot to Jonathan for the above answer. We too were faced with similar problem and triggering custom events did the trick for us. Also i would add that if malsup ajaxForm plugin is being used, we should invoke 'ajaxSubmit' instead of ajaxForm as ajaxForm doesn't submit the form.

    $('form.specialForm').on('submitAJAX',function(e) {
        $(this).ajaxSubmit({
           target: '#query_output', 
           beforeSubmit:  showLoading,
           success:       hideLoading
       });
   });


来源:https://stackoverflow.com/questions/9001274/better-way-to-temporarily-disable-ajax-submission-on-ajaxform-plugin

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