AJAX通过ID绑定表单后无法提交数据的问题求助
问题解决方法
1. 修正HTML里的表单ID错误
你在HTML里给表单写的ID带了多余的#符号,这是核心问题:
- 把
<form id="#next">改成<form id="next"> - 把
<form id="#log_out">改成<form id="log_out">
ID属性的取值本身不需要加#,#只是jQuery选择器里用来定位ID元素的标记,不是ID值的一部分。之前用$('form')能生效是因为它选中了所有表单,不管ID写没写错。
2. 修正AJAX的数据序列化逻辑
原来的$('form').serialize()会把页面上所有表单的内容都序列化提交,这显然不合理,应该只序列化当前提交的表单:
把 data: $('form').serialize() 改成 data: $(this).serialize()
这里的this指向触发submit事件的#next表单,只会序列化这个表单里的登录和密码数据。
修正后的完整JS代码
$(function () { $("#next").on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'post', url: 'check_user.php', dataType: 'json', data: $(this).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); } }); }); });
修正后的完整HTML代码
<!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> </html>
内容的提问来源于stack exchange,提问作者kirvel
相关产品推荐
相关产品推荐

