【发布时间】:2018-05-07 15:58:24
【问题描述】:
我今天在使用 AJAX 表单时遇到了一些问题。我已经尝试了很多东西,但无法让它发挥作用。
我的 jQuery 应该阻止表单提交。它必须通过AJAX。然而,它似乎忽略了 event.preventDefault();并提交表单。
表单是“单页”的一部分。单页是通过 AJAX 加载的页面。该表单是一个标准的带有POST方法的表单。
问题: 为什么 event.preventDefault() 不起作用,我该如何解决这个问题?
表格:
<form id="comment-form" action="commentsystem.php" method="post">
<input type="text" placeholder="Write a comment..." name="commentTxt" />
<input type="hidden" value="'.$row['id'].'" name="postID" />
<div class="submit-btn">
<img src="assets/images/checkmark.svg" />
<input type="submit" value="" />
</div>
jquery:
$('#comment-form').on('submit', function (event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $('#comment-form').serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: formData,
success: function (response) {
$('.comment-container').append(response);
}
});
});
评论系统.php:
$sql = "INSERT INTO comments (postID, userID, comment) VALUES ('$_POST[postID]', '$_SESSION[id]', '$_POST[commentTxt]')";
if ($conn->query($sql)===TRUE){
echo '<p><span class="username">'.$_SESSION[id].'</span>'.$_POST[commentTxt].'</p>';
} else{
echo 'Something went wrong while sending your comment.';
}
【问题讨论】:
-
从函数返回
false -
@DanielKrom - 如果正在使用
event.preventDefault,那不应该是必要的/有用的:.submit() docs -
更改 -
$(form).attr('action')- 到$('form').attr('action') -
或者到 -
$(this).attr('action') -
顺便说一句,您可以使用 firefox Web 开发人员功能检查 javascript 错误,这样您就知道要修复哪个错误。
标签: php jquery ajax forms preventdefault