简体   繁体   中英

Web2py: how to cancel a form submission within a LOADed component

If I have a web2py view (say tmp.load), I can force the form not to submit by returning false from the on submit handler.

<form onsubmit="return false;"><input type="text"><input type="submit" /></form>

That works when I view it directly: this form never submits. But if I load this view using

{{=LOAD('tmp.load', ajax=True)}}

Then the form submits, even though I was expecting it not to. So how do I write a LOAD component that contains a form which can be programmed not to submit if certain js conditions are met?

web2py.js automatically sets up event handlers for forms in components in order to submit them via Ajax. One possible approach is to intercept web2py's Ajax submission by setting up an ajax:beforeSend event handler. For example, in the view of the component (ie, tmp.load ), something like:

<script>
$(document).on('ajax:beforeSend', function(e, xhr, settings) {
  if (settings.type === 'POST') {
    if(abortAjaxSubmission) {
      xhr.abort();
      $.web2py.enableFormElements($('form#myform'));
    }
  }
});
</script>

In the above, abortAjaxSubmission represents the condition where you want to stop the submission. The selector form#myform represents the form in the component (you need to re-enable the form elements because web2py disables them upon submission but only re-enables them upon completion of the Ajax request, which won't happen if you abort).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM