Javascript AJAX评论系统,AJAX不工作
我正在为我正在创建的博客制作一个评论系统,目前我有两个问题。表格出现在每个帖子下面。但只在最高职位上有效。其余的表单根本不起作用 我遇到的另一个问题是,我正在使用ajax,表单确实会将记录添加到SQL中,但我仍然需要刷新页面才能显示它。我希望它在添加后立即自动显示 tl:dr 两个问题:Javascript AJAX评论系统,AJAX不工作,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,我正在为我正在创建的博客制作一个评论系统,目前我有两个问题。表格出现在每个帖子下面。但只在最高职位上有效。其余的表单根本不起作用 我遇到的另一个问题是,我正在使用ajax,表单确实会将记录添加到SQL中,但我仍然需要刷新页面才能显示它。我希望它在添加后立即自动显示 tl:dr 两个问题: 唯一有效的表单是第一个帖子下的第一个表单,其他表单根本不起作用 Ajax不会自动显示注释,需要刷新以显示它们 代码: JQuery 函数post() { var comment=document.getElem
函数post()
{
var comment=document.getElementById(“comment”).value;
var name=document.getElementById(“name”).value;
var mail=document.getElementById(“邮件”).value;
var post_id=document.getElementById(“post_id”).value;
如果(评论、姓名和邮件)
{
$.ajax
({
键入:“post”,
url:'php/comment.php',
数据:
{
用户通信:评论,
用户名:name,
用户_mail:mail,
post_id:post_id,
},
成功:功能(响应)
{
document.getElementById(“comments”).innerHTML=response+document.getElementById(“comments”).innerHTML;
document.getElementById(“注释”).value=“”;
document.getElementById(“名称”).value=“”;
document.getElementById(“邮件”).value=“”;
}
});
}
返回false;
}
Index.php
留下评论:
您的父循环正在生成多个注释表单,它们都具有相同的id。对于整个文档,id应该是唯一的。参考也许这会导致除第一个之外的其他评论表单无法工作
你的第二个问题不是问题。这是服务器工作方式的一般行为。当您使用ajax时,它将数据发送到服务器,服务器将数据存储在数据库中。服务器的工作完成了。如果不刷新页面,则无法将数据发送回页面并更新页面内容。您可以在发布到服务器后启动另一个ajax调用,以刷新页面内容
尽管这与问题无关。尽量使用单引号和双引号。你不应该随意选择它们。选择一个并始终如一地使用它们。是的,一定要努力学习PDO或mysqli。我建议使用PDO。我测试了您的所有代码。它正在工作。我对它进行了全面的评论,所以在代码中搜索“NB”(lat.表示“Nota bene”),以查看我是否做了相关的更改。我将在这里描述它的一些问题,如果可以的话,我也会给你一些建议。最后,我将插入三个已更正的页面
问题:
- 一个大问题是,您在中使用了
$id\u post
变量
SELECT
sql语句(在comment.php
中),该语句不存在
在comment.php
code中
- 其他问题:DOM元素具有相同的ID。里面的DOM元素
循环表单必须具有唯一的
id
属性。你一定一直都有
html元素中唯一的id
属性。把表格给他们
id=”“
例如
- 在更多的地方还存在其他问题。我总的来看,,
所以你得读我的密码
建议:
- 使用
mysqli
而不是mysql
函数,因为mysql
扩展已从PHP>=7.0中完全删除
- 使用异常处理,尤其是在处理db访问时
- 不要从php内部编写HTML代码。如果需要,可以选择php和html
例如,希望,但不要做
echo”“
。这
如果您使用一个IDE来格式化您的
html代码。如果这段代码在php中,您就没有机会这样做
美化过程。因此,您可能会错过重要的html标记
不知道,因为IDE没有显示标记的位置
这一页真的不见了
- 在html标记中:使用与
id
相同的name
。示例:id=mail
,name=mail
。例外:收音机
按钮、复选框和所有可以组成一个组的标记。然后,每个
标记将具有唯一的id,但所有标记都将接收相同的id
名字
- 在它们内部使用“”和“”。保持这个“标准”,你会发现它比相反的要好得多
更正页:
Index.php:
注:标题
通过
">
留下评论:
您的代码易受SQL注入攻击,您需要修复
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
<!-- NB: Added my scripts for testing -->
<link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
<script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
if (!$result) {
throw new Exception('The query could not be executed!');
}
while ($row = mysqli_fetch_array($result)) {
// NB: Unified $post_id name overall (instead of $id_post).
$post_id = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
?>
<!-- Blog Post Content Column -->
<!--
NB: Extracted html code from php and added here, where it should be.
-->
<h1>
<?php echo $post_title; ?>
</h1>
<p class="lead">
by <a href="#">Matt</a>
</p>
<hr/>
<p>
<span class="glyphicon glyphicon-time">
<?php echo $post_date; ?>
</span>
</p>
<img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
<hr/>
<p class="lead">
<?php echo $post_first; ?>
</p>
<p>
<?php echo $post_second; ?>
</p>
<hr/>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
<!--
NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute!
So: transfered post_id value to post() function as argument. See js too.
-->
<!--
NB: Added post_id to the "id" attributes. See js too.
-->
<div class="form-group">
<input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<!--
NB: Added new "comments" outer-container in order to append
new comment to it and added post_id value into its "id" attribute.
See the js too.
-->
<div id="comments<?php echo $post_id; ?>" class="comments-container">
<?php
$resultComments = mysqli_query($con, 'SELECT * FROM `comment` WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
if (!$resultComments) {
throw new Exception('The query could not be executed!');
}
while ($affcom = mysqli_fetch_assoc($resultComments)) {
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<!-- Posted Comments -->
<!--
NB: deleted id attribute "comments", because I added an outer
container to hold the insert results, e.g. the div
with the class "comments-container".
-->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="<?php echo $grav_url; ?>" >
</a>
<div class="media-body">
<?php echo $name; ?>
<h4 class="media-heading">
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
<?php
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
</head>
<body>
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
$comment = $_POST['user_comm'];
$name = $_POST['user_name'];
$mail = $_POST['user_mail'];
$post_id = $_POST['post_id'];
// NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
// Use UNIX timestamps for dates, so that you make good date calculations.
$date = date("Y-m-d");
// NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
$insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
if (!$insert) {
throw new Exception('The query could not be executed!');
}
// NB: Replaced $id_post with $post_id.
$select = mysqli_query($con, "SELECT * FROM `comment` WHERE post_id = '$post_id' ORDER BY `date` DESC");
if (!$select) {
throw new Exception('The query could not be executed!');
}
if ($row = mysqli_fetch_array($select)) {
$name = $row['name'];
// NB: Added email, because it wasn't provided.
$email = $row['mail'];
$comment = $row['comment'];
$date = $row['date'];
// NB: It wasn't provided, so I added the same value as in index.php.
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<div class="media">
<a class='pull-left' href='#'>
<!--
NB: Where is your $grav_url value?! I added one of mine for testing.
-->
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'>
<?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
// NB: Don't use exit(). Let the code flow further, because
// you maybe want to close the db connection!
// exit();
}
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
</body>
</html>
// NB: Added post_id as parameter. See form too.
function post(post_id) {
// NB: Added post_id value to the "id" attributes. See form too.
var comment = document.getElementById("comment" + post_id).value;
var name = document.getElementById("name" + post_id).value;
var mail = document.getElementById("mail" + post_id).value;
if (comment && name && mail) {
$.ajax({
type: 'post',
url: 'php/comment.php',
data: {
user_comm: comment,
user_name: name,
user_mail: mail,
post_id: post_id
},
success: function (response) {
// NB: Comments-post_id is now an outer container. See form.
// NB: Added post_id value to the "id" attributes. See form too.
document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
document.getElementById("comment" + post_id).value = "";
document.getElementById("name" + post_id).value = "";
document.getElementById("mail" + post_id).value = "";
}
});
}
return false;
}
// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
// var comment = $('#comment' + post_id);
// var name = $('#name' + post_id);
// var mail = $('#mail' + post_id);
//
// if (comment && name && mail) {
// var ajax = $.ajax({
// method: 'POST',
// dataType: 'html',
// url: 'php/comment.php',
// data: {
// user_comm: comment.val(),
// user_name: name.val(),
// user_mail: mail.val(),
// post_id: post_id
// }
// });
// ajax.done(function (data, textStatus, jqXHR) {
// var comments = $("#comments" + post_id);
//
// // NB: I'm not sure, not tested, too tired :-) Please recherche.
// comments.html(data + comments.html());
//
// comment.val('');
// name.val('');
// mail.val('');
// });
// ajax.fail(function (jqXHR, textStatus, errorThrown) {
// // Show error in a customized messages div, for example.
// $('#flashMessage').val(textStatus + '<br />' + errorThrown);
// });
// ajax.always(function (data, textStatus, jqXHR) {
// //...
// });
// }
//
// return false;
//}
// ******************************************************************************