【问题标题】:Commenting form with ajax not responding用ajax评论表单没有响应
【发布时间】:2015-08-18 13:30:51
【问题描述】:

我目前正在编写一个带有评论系统的博客。我想使用 AJAX,所以提交评论后页面不需要刷新。 但是,AJAX 进程不会将表单信息发送到我的 php 脚本。在我的 Javascript/Ajax 代码中,我使用警报函数编写了几个“断点”,以查看正在执行 AJAX 脚本中的哪些代码。所有的警报功能都可以正常工作,因此希望这意味着 AJAX 脚本正在执行。但是没有信息发送到我的数据库。

请你看看我下面的代码并帮助我找出我做错了什么吗?

我的 HTML 表单:

<form method="post" action="" id="commentform">
 <ul>
  <li> <label>Your name:</label>
  <input type="text" name="name" id="name" required> 
  </li>
  <li> <label>Comment:</label><br id="commentformbr">
  <textarea name="comment" id="comment" rows="3" wrap="hard" required></textarea>
  </li>
 </ul>
 <div id="buttondiv">
  <input type="submit" value="Post comment" id="submit">
  <input type="reset" value="Reset form">
 </div>
</form>

我的 AJAX 脚本(在 HTML 文档的 head-tag 中):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> 
<script type="text/javascript">
$(document).ready(function(){
    $('#commentform').on('submit',function(e){
        e.preventDefault();
        var name = $("#name").val();
        var comment = $("#comment").val();
        alert("After preventDefault");
        $.ajax({
            url: "commentsprocess.php",
            type: "POST",
            cache: false,
            data: {
                'user_name': name,
                'user_comm': comment
            },
            success: function(response){
                alert("Start of succces-function");
                $('#all_comments').innerHTML=response + $('#all_comments').innerHTML;
                $('form').reset();
                alert("End of succces-function");
            },
            error: function(e) {
                alert(e);
            }
        });
    });
});
    </script>

最后,我的 php 脚本应该在名为“blogcmets”的表中插入评论和评论者的姓名。 PHP 脚本还返回最新的评论:

<?php
include '../phpprocesses/phpfunctions.php';
require_once '../setupsql.php';

$connection = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if($connection->connect_error) die($connection->connect_error);

if(isset($_POST['user_comm']) && isset($_POST['user_name'])) {
//get_post-function from phpfunction.php is used to sanitize the posted strings.
    $comment = get_post($connection,'user_comm');
    $name = get_post($connection,'user_name');

    //Inserts the comment in the 'blogcomments' table
    $query = "INSERT INTO blogcomments VALUES" . "(NULL,'$name','$comment',CURRENT_TIMESTAMP)";
    $result = $connection->query($query);
    if(!$result) die($connection->error);

    //Returns the latest comment to the comment-page
    $id = $connection->insert_id($result);
    $query = "SELECT * FROM blogcomments WHERE name='$name' and comment='$comment' and id='$id'";
    $result = $connection->query($query);
    if(!$result) die($connection->error);

    $result->data_seek(0);
    $row = $result->fetch_array(MYSQLI_ASSOC);
    $name = $row['name'];
    $comment = $row['comment'];
    $time = $row['timestamp'];

    echo <<<_END
        <div class="commentdiv">
            <h4>Posted by: <?php echo $name;?></h4>
            <h5><?php echo $time;?></h5>
            <p><?php echo $comment;?></p>
        </div>
_END;
}
?>

【问题讨论】:

  • 快速查看,不要在表单中添加“操作”...您可以使用开发人员工具查看正在提交的请求吗?
  • @avrono 似乎是同一页....;) 但没有提交表单。
  • 所以删除该操作,然后查看...
  • 感谢您的回复!我删除了动作属性,但仍然没有任何反应。但是,现在我没有收到“成功结束”警报。还有什么想法吗?您建议我使用哪些开发者工具?
  • 有点困惑。您是否检查了调试器(Chrome 按 F12)并查看您的 POST 在 chrome 调试器的网络选项卡中是否成功?您应该将数据视为标题的一部分。如果是,那么您可以排除一部分并专注于处理 sql 插入的部分(commentprocess.php)

标签: jquery ajax


【解决方案1】:

所以,在得到您的帮助并尝试自己调试之后,我终于设法让我的博客上的评论页面正常工作。您可以看到以下更改的重写和 cmets。 我的 HTML 表单。这里没有比删除“action”属性更多的变化:

<form method="post" id="commentform">
<ul>
    <li> <label>Your name:</label>
     <input type="text" name="name" id="name" required>
</li>
 <li> <label>Comment:</label>
     <br id="commentformbr">
     <textarea name="comment" id="comment" rows="3" wrap="hard" required></textarea>
</li>
  </ul>
<div id="buttondiv">
  <input type="submit" value="Post comment" id="submit">
  <input type="reset" value="Reset form">
</div>
</form>

我的 AJAX 脚本。所做的更改是:

1) 警报功能已被删除,cmetsprocess.php 的 url 也已更改(细微更改)。

2) 我没有使用 "$('...').innerHTM L= response + $('...').innerHTML" 将最近的评论放在评论部分的最前面,而是替换了它使用 JavaScript 函数 prepend() 代替。这会将来自 cmetsprocess.php 脚本的响应首先放在指定目标中。

3) 我没有使用显然不起作用的 $('form').reset(),而是使用 $('#name').val("") 重置了评论字段中的两个输入字段而是。

$(document).ready(function(){
    $('#commentform').on('submit',function(e){
        e.preventDefault();
        var name = $("#name").val();
        var comment = $("#comment").val();
        $.ajax({
            url: "../phpprocesses/commentsprocess.php",
            type: "POST",
            cache: false,
            data: {
                'user_name': name,
                'user_comm': comment
            },
            success: function(response){
                $('#all_comments').prepend(response);
                $('#comment').val("");
                $('#name').val("");
            },
            error: function(e) {
                alert(e);
            }
        });
    });
});

最后但同样重要的是,我的 cmetsprocess.php 脚本处理 AJAX 调用。这份文件实际上一直是主要问题。已进行的更改是:

1) 'phpfunctions.php' 中的 get_post() 函数无法被调用。我用 htmlentities() 替换了它,它清理了 $_POST 字符串(我也应该从 MySQL 注入中清理它)。

2) 我没有回显输出,而是将其编写为纯 HTML。

<?php
require_once '../setupsql.php';

$connection = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if($connection->connect_error) die($connection->connect_error);

if(isset($_POST['user_comm']) && isset($_POST['user_name'])) {
    //get_post-function from phpfunction.php is used to sanitize the posted strings.
    $comment = htmlentities($_POST['user_comm']);
    $name = htmlentities($_POST['user_name']);

    //Inserts the comment in the 'blogcomments' table
    $query = "INSERT INTO blogcomments VALUES" . "(NULL,'$name','$comment',CURRENT_TIMESTAMP)";
    $result = $connection->query($query);
    if(!$result) die($connection->error);

    //Returns the latest comment to the comment-page
    $id = $connection->insert_id;
    $query = "SELECT * FROM blogcomments WHERE name='$name' and comment='$comment' and id='$id'";
    $result = $connection->query($query);
    if(!$result) die($connection->error);

    $result->data_seek(0);
    $row = $result->fetch_array(MYSQLI_NUM);
    $name = $row[1];
    $comment = $row[2];
    $time = $row[3];
?>
<div class="commentdiv">
    <p><?php echo $comment;?></p>
    <a href="#" class="deletecomment">Delete comment</a>
    <span class="commname"><?php echo $name;?></span>, <span class="commtimestamp"><?php echo $time;?></span>
</div>
<?php
$connection->close();
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多