好吧,经过几天的搜索和阅读,我仍然无法让它发挥作用,所以这是我最后的机会。请记住,我是Ajax和JS的新手。
我有一个评论墙,你可以在那里给页面上的其他人留下一条漂亮的小消息,它运行得很好,但现在我想添加一些ajax,这样它每10秒自动刷新一次,并获得最新的评论。
问题是,我让整个网站显示在div中,而不是评论。
我有一个js文档,代码如下
(function update() {
$.ajax({
type : 'GET',
url : 'index.php',
success : function(data){
$('#cmt_wall_container').html(data);
},
}).then(function() {
setTimeout(update, 10000);
});
})();
我的Index.php页面包括以下
<?php include_once 'connect.php'; ?>
<?php
$cmt_list = "";
$sql = mysqli_query($con, "SELECT * FROM cmt ORDER BY id DESC LIMIT 10");
$cmtCount = mysqli_num_rows($sql);
if($cmtCount > 0){
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$comment = $row["comment"];
$cmt_list .="<div class='post-container'><p class='post-comment'>$comment</p></div>";
}
} else {
$cmt_list = "leave a comment";
}
?>
<head>stuff..</head>
<body>
<div id="cmt_wall_container">
<?php echo $cmt_list; ?>
</div>
</body>
我希望这足够清楚!非常感谢你,你真的是我最后的希望!!!!!
请尝试以下内容。。。
JS脚本:
function update() {
$.post( "index.php", { grab: "comments"}).done(function( data ) {
$('#cmt_wall_container').html(data);
setTimeout(update, 10000);
});
}
PHP脚本:
<?php
include_once 'connect.php';
$cmt_list = "";
$sql = mysqli_query($con, "SELECT * FROM cmt ORDER BY id DESC LIMIT 10");
$cmtCount = mysqli_num_rows($sql);
if($cmtCount > 0){
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$comment = $row["comment"];
$cmt_list .="<div class='post-container'><p class='post-comment'>$comment</p></div>";
}
} else {
$cmt_list = "leave a comment";
}
// Return Results To Ajax And Exit
if (isset($_POST['grab']) && $_POST['grab']==="comments") {
echo $cmt_list;
exit;
} // Else Load Page As Normal
?>
<head>stuff..</head>
<body>
<div id="cmt_wall_container">
<?php echo $cmt_list; ?>
</div>
</body>
通过使用isset,您可以检测您的请求是否来自ajax,并且只返回注释,否则您将正常加载页面重置。。这是一种方法。
请注意,这仍然适用于$_GET。。如果需要,只需使用退出选项将$_POST更改为$_GET即可。。你不需要把你的整个网站包装在其他声明中。。其更清洁的
那么,将您的ajax url更改为index.php?grab=注释,并将其添加到PHP代码下面。
if (isset($_GET['grab']) && $_GET['grab']==="comments") {
echo $cmt_list;
exit;
}
通过使用这种方法,您还可以使用grab=admin_comments或您想要的方式等选项来控制您的评论。
它应该像8BitProgrammer建议的一样工作
(function update() {
$.ajax({
type : 'GET',
url : 'index.php?comments=true',
success : function(data){
$('#cmt_wall_container').html(data);
},
}).then(function() {
setTimeout(update, 10000);
});
})();
php:
<?php include_once 'connect.php'; ?>
<?php
$cmt_list = "";
$sql = mysqli_query($con, "SELECT * FROM cmt ORDER BY id DESC LIMIT 10");
$cmtCount = mysqli_num_rows($sql);
if($cmtCount > 0){
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$comment = $row["comment"];
$cmt_list .="<div class='post-container'><p class='post- comment'>$comment</p></div>";
}
} else {
$cmt_list = "leave a comment";
}
if ($_GET["comments"]):
?>
<?php echo $cmt_list; ?>
<?php
else :
?>
<head>stuff..</head>
<body>
<div id="cmt_wall_container">
<?php echo $cmt_list; ?>
</div>
</body>
<?php
endif;
?>