表单数据不会通过 AJAX 通过 id 发送



我想要下面的ajax请求处理表单数据从表单"#next"id:

$(function () {
$("#next").on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});

这里是包含表单的文件:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/auth_style.css">
<title>Authentication</title>
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script src="js/authentication_ajax.js"></script>
<noscript>JS is disabled. Enable js to continue</noscript>
</head>
<body>
<h1 id="header">Enter your data here</h1>
<form id="#next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="#log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>
</body>

有趣的是,当我只使用$('form').on('submit', function (e) {时,它工作得很好。

您有两个错误,第一个是如何使用id,在id中不使用#而只使用名称,并进入选择器,您可以使用$('#name')。第二个问题是关于serialize()的选择器,在这种情况下,您可以直接使用e.target,如:

$(function() {
$("#next").on('submit', function(e) {
e.preventDefault();
console.log($(e.target).serialize());
/*
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $(e.target).serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="header">Enter your data here</h1>
<form id="next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>

最新更新