【发布时间】: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)