我的网站上有一个简单的聊天系统。当我点击消息列表中的用户时,数据会使用AJAX从数据库中提取。这个脚本加载聊天的PHP内容:
function toggleMail(other) {
jQuery.ajax({
url: "fetch_message.php",
data:'other='+other,
type: "POST",
success:function(data){
$('#message').show();
setInterval(function(){
var scrollpos = $('#messages').scrollTop();
$('#message').html(data);
$('#messages').scrollTop(scrollpos);
}, 1000);
}
});
我的PHP脚本fetch_message.PHP包含如下内容:
//--Some PHP code --
<div class="mail_header"><?php xxx ?></div> //with some information about the chat
<div class="mail_messages"><?php xxx ?></div> //with the conversation itself
<div class="mail_replybox"><?php xxx ?></div> //with the textarea to respond to the chat
我想每1秒自动刷新一次聊天。问题是,它不仅刷新了对话本身,还刷新了mail_header和mail_replybox,这当然不应该发生。mail_header和mail_replybox需要来自PHP代码的数据,因此它们都位于同一个PHP脚本中。
有人知道我如何只刷新中间部分,即对话,而不刷新其他div吗?我已经在这方面工作了好几天了,无法让它发挥作用。。。
您将setInterval
放错了位置:服务器请求不会重复,因此相同的数据会一次又一次地放在message
元素中。
为了只刷新聊天部分,您可以在服务器请求中(即向PHP)提供一个参数,以便它知道是生成头、消息和回复框,还是只生成消息。
建议的PHP代码更改:
<?php
if (!isset($_POST['refresh'])) { // check absence of new argument
?>
<div class="mail_header"><?php xxx ?></div>
<div class="mail_messages"><?php xxx ?></div>
<div class="mail_replybox"><?php xxx ?></div>
<?php
} else { // only refresh messages:
echo xxx; // only chat content, without the <div class="mail_messages">
}
?>
然后在您的JavaScript中:
function toggleMail(other, refresh) { // second parameter added
// define arguments to pass in the request:
var data = { other: other };
if (refresh) data.refresh=1; // define new request parameter
jQuery.ajax({
url: "fetch_message.php",
data: data,
type: "POST",
success:function(data){
var scrollpos = $('#messages').scrollTop();
if (refresh) { // only populate chat
$('#message .mail_messages').html(data);
} else { // populate the whole lot
$('#message').html(data).show();
}
$('#messages').scrollTop(scrollpos);
// Send new refresh request in 1 sec:
setTimeout(function(){
toggleMail(other, 1)
}, 1000);
}
});
}
对toggleMail的原始调用可以保持原样,只需要第一个参数。