在哪里使用 preventDefault();在 jQuery 中停止提交表单数据

where to use preventDefault(); in jquery to stop submit form data

本文关键字:提交 数据 表单 jQuery preventDefault 在哪里      更新时间:2023-09-26

我正在尝试使用jquery向php提交表单数据。我不想默认提交。代码工作正常。我不知道在哪里使用event.preventDefault();

下面是我的jquery代码

<script>
 $(function () {
             $("#submit").click(function () {
                var password = $("#password").val();
                var confirmPassword = $("#confirm_password").val();
                var dataString='password='+ password + 'confirmPassword='+ confirmPassword;
                if (password != confirmPassword) {
                    alert("Passwords and Confirm Password Should match.");
                    return false;
                }
                else{
                $.ajax({
        type: "POST",
        url: "update-password.php",
        data: dataString,
        success: function(result){
            alert(result)
        }
      });

     }
   });
});
</script>  

不要使用click事件来控制表单提交。它被键盘表单提交绕过!始终使用 submit 事件。

当您通过 Ajax 提交表单时,您可以使用e.preventDefault()立即停止提交

例如

$(function() {
 $("form").submit(function(e) {
   e.preventDefault();
   var password = $("#password").val();
   var confirmPassword = $("#confirm_password").val();
   var dataString = 'password=' + password + 'confirmPassword=' + confirmPassword;
   if (password != confirmPassword) {
     alert("Passwords and Confirm Password Should match.");
   } else {
     $.ajax({
       type: "POST",
       url: "update-password.php",
       data: dataString,
       success: function(result) {
         alert(result)
       }
     });
   }
 });
});

注意:由于您没有对提交执行任何特殊操作,因此除非需要,否则最好不要使用Ajax。只是有条件地返回truefalse.

返回 false 与 e.preventDefault() e.stopPropagation() 相同。

例如

$(function() {
 $("form").submit(function() {
   var password = $("#password").val();
   var confirmPassword = $("#confirm_password").val();
   var dataString = 'password=' + password + 'confirmPassword=' + confirmPassword;
   if (password != confirmPassword) {
     alert("Passwords and Confirm Password Should match.");
     return false
   }
 });
});

一般建议:不要使用alert与用户交互。改为在页面上显示验证消息。