0

我正在尝试将评论表单中的数据保存到 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);

4

2 回答 2

1

在 ajax 中,您可以删除dataType: 'json',并删除if(rsp.success) {并发出简单的警报

$.ajax({
        url: url,
        data: data,
        success: function(data) {
                alert("Comment Successfully Added!");
                alert(data);
        }
});

在 php 而不是您正在使用的 return 中,使用 echo

echo $resp;

至少你会看到是否有错误

之后,您可以开始使用 json 代码

在 php

echo json_encode($resp);//as soon as $resp is an array

在ajax中你可以这样提醒alert(data.keyofthearray)

于 2013-03-05T22:54:53.593 回答
1

为了防止表单提交(正在发生的事情)使用onsubmit="return ajaxSubmit(this);"

您的 ajax 代码中也有语法错误。你永远不会关闭if

var data = $(formEl).serialize();
$.ajax({
    url: url,
    data: data,
    dataType: 'json',
    success: function(data) {
        if(data.success) {
            alert("Comment Successfully Added!");
        }
    }
});
于 2013-03-05T22:56:29.103 回答