我正在尝试将简单的表单数据从索引页发送到PHP函数checklogin.php。我发现,没有数据(无论是序列化的还是直接输入的)都无法传递到PHP函数。我知道一个事实,就是调用了jQuery函数,而且我也知道调用了PHP文件,因为我放入了各种post函数。
当我使用action="checklogin.php"
直接从表单提交数据时,正确接收到了$ _POST数据,并且可以对其进行处理。但是,当使用jQuery拦截表单提交时,不会接收到任何数据。
需要注意的一件事是,实际的登录表单HTML是从另一页插入的,这使我可以在多个页面上工作,而不是一个大索引文件。
表格-login.php
<form id="loginform" name="loginform" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login</strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="username" type="text" id="username"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="password" type="text" id="password"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
提交事件挂钩-Index.php
$( document ).ready(function() {
$.post("login.php", function(data) { // retrieve login form from other page.
$("#page5").html(data);
$('#loginform').submit(function () {
event.preventDefault();
var formData = $(this).serialize();
console.log("Form Data: " + formData); // this is not blank
$.post("checklogin.php", formData, function(data) {
// post-login actions
})
});
});
})
});
checklogin.php(直到问题解决为止是临时的)
<?php
print_r($_POST);
?>
如我所说,即使直接输入,例如“ username = test $ password = blah”,而不是“ formData”,也会导致一个空的$ _POST数组。我也尝试过使用ajax等效的post调用,但是没有运气。
JavaScript控制台输出
// console.log line above $.post
Form Data: username=test&password=blah
// Result from PHP print_r
Array
(
)
最佳答案
使用.on()
由于元素是动态添加的,因此无法将事件直接绑定到它们。因此,必须使用Event Delegation。
$(document).on('submit','#loginform',function () { //code here }
或更好地使用
$('#page5').on('submit','#loginform',function () { //code here }
句法
$( elements ).on( events, selector, data, handler );