简体   繁体   English

阻止表单数据在http请求后提交

[英]Prevent form data from submitting after http request

The following code prevents submitting the form data 以下代码阻止提交表单数据

$('#dataForm').submit(function (e) {
   e.preventDefault();
});

My problem is how to achieve that in case there's an ajax call which takes time to get response. 我的问题是,如果存在需要花费时间才能获得响应的ajax调用,该如何实现。 So the form will not wait until the request get the response 因此表单不会等到请求获得响应

$('#dataForm').submit(function (e) {
  ajaxCallAsPromise().then(function (data){
     if (data == true)
       {
         e.preventDefault(); //this will not work
       }
  });
  //any codes here works normally ..
});

My purpose to wait until get the request response then use- 我的目的是等待直到获得请求响应,然后使用-

e.preventDefault();

You will have to call preventDefault() immediately to stop the form submission. 您必须立即调用preventDefault()才能停止提交表单。 There's no way to avoid that as the AJAX call is asynchronous and you'll need to wait for it. 无法避免这种情况,因为AJAX调用是异步的,您需要等待它。

However you can call submit() on the form element itself after the AJAX call completes in order to subvert the jQuery event handler and allow the form to be sent to the server, like this: 但是,您可以在AJAX调用完成后在form元素本身上调用submit() ,以颠覆jQuery事件处理程序并将表单发送到服务器,如下所示:

$('#dataForm').submit(function(e) {
  e.preventDefault(); // stop the submission
  var form = this;

  ajaxCallAsPromise().then(function(data) {
    if (!data) { // if data is verified, submit the form again
      form.submit();
    } else {
      // presumably you want to tell the user the data is invalid here...
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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