'Alajax'Jquery简单表单提交。如果表格未经验证,如何阻止提交?

时间:2016-04-22 09:59:57

标签: javascript jquery ajax forms

我正在寻找一个简单的JQuery插件,以便通过Ajax轻松提交表单,我找到了Alajax,我发现它很方便,因为它集成到一个典型的HTML表单中并完成所有工作。不幸的是,我不明白如果没有验证如何防止表格被汇总(官方网站的文档很差,作者也没有回复我的邮件)。

例如,通过Ajax提交以下表单:插件拦截表单,获取'name'属性并将 send.php 称为普通表单

<form id="myform" action="send.php">
    <input type="text" name="firstname"
    <input type="submit" value="Submit">
</form> 

<script>
    $(document).ready(function (){
        $("#myform").alajax();
    });
</script>

Alajax有一些options,如下所述:

$('#myform').alajax({
    type: '' // Type of return value. Default is "text". Other values are: "json", "xml", "jsonp"
    beforeSend: function (){} // Code to run before sending the form
    success: function(){} // Code to run when the AJAX call success
    error: function(){} // Code to run when error occures
});

但是以下代码仍然提交表单:

$('#myform').alajax({
    beforeSend: function (){
        // Validation code is here. Suppose that form is not validated,
        return false; // this should'nt stop submitting the form?
    }
});

beforeSend 选项中的代码正确执行(因为我通过调用console.log来测试它),但仍然提交了表单。如何在出错时阻止表单提交?我也试过 preventDefault 但没有成功。

1 个答案:

答案 0 :(得分:0)

您无法使用alajax阻止表单子目录。但是你可以使用另一个提交监听器来阻止事件到达alajax。

<form id="myform" action="send.php">
  <input type="text" name="firstname">
  <input type="submit" value="Submit">
</form> 

<script>
  $(document).ready(function (){

    $("#myform").submit(function(e){
      e.preventDefault();
      if(/* form is invalid */){
        e.stopImmediatePropagation();
      }
    });

    $("#myform").alajax();
  });
</script>

修改

还有另一种方法可以在beforeSend函数中throw new Error('asd');