繁体   English   中英

如何在ajax调用期间停止表单提交

[英]How to stop form submit during ajax call

我只能修改ajax调用中的代码。 当我单击名为$('#form1')表单中的提交时,会发生 ajax 调用。

$('#form1').submit(function () {
    $.ajax({
       url: 'some.php',
       type: 'POST',
       data: somedata,
       success: function (msg) {
          if (!msg) {
             // I wanna to stop '#form1' submit here,how to do that? I can only modify the code in the ajax call.
          }
       }
    });
 });

您需要在成功处理程序之前停止它。 因为函数在您的 AJAX 调用后完成执行,所以表单将在您的 ajax 调用发生时提交(当您的 ajax 调用完成时为时已晚)。

但是,是的,将 return false 放在函数的末尾。

function SubmitHandler(){
  // Your AJAX call here
  // blah blah blah

  return false;  // Stop form submit
}

如果它在成功处理程序中真的很重要,那么您可以同步执行调用。

您还可以使用preventDefault()

http://api.jquery.com/event.preventDefault/

return false 或 event.preventDefault 应该可以帮助您:

$('#form1').submit(function(){
    $.ajax({
        url:'some.php',
        type:'POST',
        data:somedata,
        success:function(msg){
        if(!msg){
            //i wanna to stop form1 submit here,how to do that?  you can only modify the code in the ajax call
        }
    }
    });
    return false;
});

要么:

$('#form1').submit(function(e){
    e.preventDefault();
    $.ajax({
        url:'some.php',
        type:'POST',
        data:somedata,
        success:function(msg){
        if(!msg){
            //i wanna to stop form1 submit here,how to do that?  you can only modify the code in the ajax call
        }
    }
    });
});

放一个

return false;

这应该停止该功能以继续

您可以将按钮类型从“提交”更改为“按钮”,然后使用 jquery form.submit() 提交表单; 根据您的条件运行。 考虑下面的示例代码:

<script>
 $(document).ready(function() {
$("#button-id").click(function() //on click at button
{

var sel=$("#input").val();

        $.post("ajax-war.php",{jid:sel,rand:Math.random() } ,function(data)
        {

          if(data=='valid') //if correct login detail
          {

$('#war_form').submit(); //Submit form
          }

          else
          {
              alert('not valid'); //will not submit form

          }
});       
});
}); 

</script>

您需要阻止表单提交

onclick="ajaxcall(); return false;"

并在您的代码中执行此操作:

 $.ajax({
  url:'some.php',
  type:'POST',
  data:somedata,
  success:function(msg){if(msg) $('#form1').submit();}
 })

假设表单的 ID 是#form1 ,您可以绑定一个提交处理程序并从中返回 false:

$.ajax({
  url:'some.php',
  type:'POST',
  data:somedata,
  success:function(msg){
    if(!msg){
     $('#form1').submit(function(){
       return false; // prevents form submit
     });
    }
  }
 })

暂无
暂无

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

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