【发布时间】:2016-07-14 14:19:53
【问题描述】:
我正在尝试在我的网站上创建一个评论系统,用户可以在其中评论并看到它出现在页面上而无需重新加载页面,有点像您在 facebook 上发表评论并立即看到它出现的方式。但是我遇到了麻烦,因为我的实现显示了用户输入的评论,但随后删除了页面上已经存在的先前 cmets(作为任何 cmets 部分,我希望用户发表评论并简单地添加到以前的 cmets)。此外,当用户 cmets 时,页面会重新加载,并在文本框中显示评论,而不是在应该显示 cmets 的文本框下方。我附上了代码。 Index.php 运行 ajax 脚本执行异步注释,并使用表单获取用户输入,在 insert.php 中处理。它还打印出存储在数据库中的 cmets。
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
插入.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
insert.php 接收用户输入,然后将其插入数据库(通过首先过滤和检查坏词)。只是不知道我要去哪里错了,被困了一段时间。任何帮助将不胜感激。
【问题讨论】:
标签: javascript php jquery mysql ajax