jquery ajax event.preventDefault()取消表单的提交动作

时间:2022-11-24 13:07:51

I create a form in html:

我在html中创建一个表单:

<form id="flog" action="https://localhost/book.php" method="post">
                    <div id="inputUser">
                        <label for="userName">User</label>
                        <input type="text" name="userName" id="userName">
                    </div>
                    <div id="inputPass">
                        <label for="password">Password</label>
                        <input type="password" name="password" id="password">
                    </div>
                    <div id="savePassword">
                        <input type="checkbox" id="savePassword" value="CheckSavePAssword">Save password
                        <br>
                    </div>
                    <input type="submit" value="Acceptar">
                </form>

And I create a submit function with JQuery:

我用JQuery创建了一个提交函数:

$("#flog").submit(function(event) {
var savePassword = false;
if($("#CheckSavePAssword").is(':checked')) {
  savePassword = true;
}
var login = new Object();
login.username = $("#userName").val();
login.pass = $("#password").val();
login.savePassword = savePassword;
var jlogin = JSON.stringify(login);
event.preventDefault();
$.ajax({
    url: "./checkLogin.php",
    type: "POST",
    dataType: "JSON",
    data: {"dataLogin" : jlogin},
    success: function(data, textStatus, xhr) {
      console.log("okk "+data);
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log("error");
        console.log(xhr);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
});

But if i don't put "event.preventDefault()" the ajax function does not run, but this line (event.preventDefault()) canceling the submit form action.What is the problem?

但是,如果我没有放“event.preventDefault()”ajax函数不运行,但这一行(event.preventDefault())取消了提交表单动作。问题是什么?

1 个解决方案

#1


1  

When you use preventDefault(), you prevent the form from undergoing a traditional POST where your page would be submitted and reloaded. You need to use a JavaScript event handler if you want to give the user some feedback after your AJAX call.

当您使用preventDefault()时,您可以阻止表单进行传统的POST,您的页面将被提交和重新加载。如果要在AJAX调用后向用户提供一些反馈,则需要使用JavaScript事件处理程序。

#1


1  

When you use preventDefault(), you prevent the form from undergoing a traditional POST where your page would be submitted and reloaded. You need to use a JavaScript event handler if you want to give the user some feedback after your AJAX call.

当您使用preventDefault()时,您可以阻止表单进行传统的POST,您的页面将被提交和重新加载。如果要在AJAX调用后向用户提供一些反馈,则需要使用JavaScript事件处理程序。