繁体   English   中英

如何基于Ajax请求的结果提交(或不提交)表单?

[英]How to submit (or not submit) a form based on the result of an Ajax request?

我的网站上有一个表单,用户可以在其中提交内容并获得结果

<form accept-charset="UTF-8" action="/submit-stuff" data-remote="true" method="post">
<!-- various form fields -->
<input type="submit" value="Run Code" id="submit-button">
</form>

在将其信息提交到后端之前,我尝试使用Javascript获得结果。 如果可以得到结果,我return false在Javascript中return false以阻止表单提交。

$('#submit-button').click(function() {
   if(canGetResults()){
     //deal with submission and then
     return false;
   }
   //the button will work as usual if canGetResults is false or there's an error 
});

这个工作正常,但是现在我想尝试通过另一个ajax请求获取结果,并且仅在失败时才提交给我的常规后端。 单击按钮后,我调用以下代码:

$.post("http://example.com/submit-stuff", json, function(data) {
  //do stuff with data
});

但是,它是异步的(因此我无法从中返回结果),因此即使其他ajax尝试失败,代码也将return false 我应该如何解决这个问题,使其仅在ajax尝试失败时才提交给我自己的后端?

我可以将$ .post更改为$ .ajax并使其同步,但是通常不建议这样做。 另外,我可以在$.post回调中提交表单,但是应该如何从那里提交整个表单? 如果出现错误或http://example.com/submit-stuff不起作用,它还会提交吗?

您的提交处理程序应始终阻止表单提交。

然后,如果Ajax代码返回OK,则应调用表单的submit()方法。 这将绕过提交处理程序并提交表单。

注:致电submit的DOM对象,而不是jQuery对象上。 jQuery习惯于从其包装器触发事件​​处理程序。

您可以在提交函数中绑定所有ajax请求,并在必要时调用.post()事件:

 $("form").submit(function(e){
     e.preventDefault(); // <-prevents normal submit behaviour

     //only post if your ajax request goes your way
     $.ajax(url,function(data){
       //argument to post or not
       if(data=="success"){ postForm(); }          
     }); 

 });

function postForm(){
    $.post(
      "/submit-stuff"
      ,$( "form" ).serialize()
      ,function(data){
         //your code after the post
      }); 
}

如果不想为postForm创建单独的函数,则可以将其放在当前被调用的包装器中。

暂无
暂无

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

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