【发布时间】:2011-10-14 09:20:23
【问题描述】:
我编写了一个非常简单的评论系统的开端。它使用 jQuery / AJAX / PHP MySQL。到目前为止,它工作正常。但是,一旦提交评论,您必须刷新页面才能显示评论。它如何在提交时显示。
我希望这里的代码不会太多,但这里分为三个部分。 jQuery / php 插入评论查询 / php select cmets 查询。
jQuery / AJAX:
$(document).ready(function() {
$('#button').click(function() {
var name = $('#name').val();
var comment = $('#comment').val();
if(name == '' || comment == '') {
$('#comment_messages').html('Please enter both fields');
} else if(name !== '' || comment !== '') {
$('#comment_messages').html('');
$.ajax({
type: 'POST',
url: 'comments.php',
data: 'name='+name+'&comment='+comment,
success: function(data) {
$('#comments_area').append(data);
}
});
}
});
});
PHP INSERT(插入 cmets):
<?php
include('init.inc.php');
if(isset($_POST['name'], $_POST['comment'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
if(!empty($name) && !empty($comment)) {
$query = mysql_query("INSERT INTO comments VALUES(NULL, '$name', '$comment', CURRENT_TIMESTAMP)");
if($query === true) {
// right here is what is being returned to success: function(data) in the ajax script. What's the best way to return the comment here?
} else {
echo 'Hmmm... that\'s odd........';
}
} else {
echo 'Please enter both fields';
}
}
?>
PHP SELECT(检索 cmets):
<?php
$query = mysql_query("SELECT * FROM comments ORDER BY time DESC LIMIT 10");
$num = mysql_num_rows($query);
if($num >= 1) {
while($fetch = mysql_fetch_assoc($query)) {
$name = $fetch['name'];
$comment = $fetch['comment'];
$time = $fetch['time'];
?>
<div id="user_comments">
<?php echo $name; ?> said at: <span id="time_stamp"><?php echo $time; ?></span><p>- <?php echo $comment; ?>
</div>
<?php
}
}
?>
更新:
在底部添加了两行:
$(document).ready(function() {
$('#button').click(function() {
var name = $('#name').val();
var comment = $('#comment').val();
if(name == '' || comment == '') {
$('#comment_messages').html('Please enter both fields');
} else if(name !== '' || comment !== '') {
$('#comment_messages').html('');
$.ajax({
type: 'POST',
url: 'comments.php',
data: 'name='+name+'&comment='+comment,
success: function(data) {
$('#comments_area').append('<b>'+name+'</b><p>- '+comment);
$('#comment_messages').html(data);
}
});
}
});
});
【问题讨论】: