我有一个类似下面的表格:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
我是 AJAX 的新手,我想要完成的是当用户单击提交按钮时,我希望 mail.php
脚本在后台运行而不刷新页面。
我尝试了类似下面的代码,但是,它似乎仍然像以前一样提交表单,而不是我需要它(在幕后):
$.post('mail.php', $('#myForm').serialize());
如果可能,我想获得使用 AJAX 实现此功能的帮助,
提前致谢
最佳答案
您需要阻止默认操作(实际提交)。
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
关于javascript - AJAX:提交表单而不刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14235596/