我正在尝试将评论表单中的数据保存到 MySQL 数据库中,然后使用该评论更新页面,而无需用户刷新。类似于 Facebook 评论的工作方式。
我到处寻找答案,但没有找到适合我需要的答案。
这是将表单数据提交到 php 脚本的 AJAX:
var ajaxSubmit = function(formEl) {
// fetch where we want to submit the form to
var url = $(formEl).attr('action');
// fetch the data for the form
var data = $(formEl).serializeArray();
// setup the ajax request
$.ajax({
url: url,
data: data,
dataType: 'json',
success: function(data) {
if(rsp.success) {
alert("Comment Successfully Added!");
}
});
return false;
}
我知道该页面当前不会使用此脚本更新,因为我正在发出警报。但是,当我提交数据时,我将被带到/ajax/comment.process.php
调用insertComment()
函数并将评论插入数据库的页面。我现在在alert()
函数中有这个函数,但success()
我什至没有得到它。
我想要的是提交评论时,用户不会离开当前页面,它只是更新了他们刚刚提交的内容。
这是代码/ajax/comment.process.php'
session_start();
include_once('../classes/comment.class.php');
include_once('../classes/db.class.php');
$user_id = $_SESSION['user_id'];
$db = new DBConnection;
$comments = new Comment($db);
$blog_id = intval($_POST['blogID']);
$addCom = $comments->addComment($user_id);
if($addCom === FALSE) {
$resp = "<span class='error'>Error adding comment</span>";
} else {
$resp = $comments->getComments($blog_id);
}
return $resp;
此脚本调用insertComment()
将评论保存到数据库的函数,然后如果返回 true,它会调用getComments()
检索特定帖子的评论并将它们存储在数组中的函数。
评论已成功保存到数据库,但我被重定向到ajax/comment.process.php
空白页面。如何使用他们发布的评论更新当前页面而无需刷新页面?我认为返回$resp
变量会做到这一点,然后我可以做一个foreach()
循环来显示它们,但显然情况并非如此。
编辑:我已经实现了下面答案中建议的一切,但我还没有解决这个问题。/ajax/comment.process.php
即使我有这三件事应该阻止提交表单,该表单仍然被提交preventDefault();
:return false;
和return ajaxSubmit(this);