jquery ajax - setinterval自动刷新脚本的一部分

时间:2016-05-01 19:35:08

标签: javascript php jquery html ajax

我的网站上有一个简单的聊天系统。当我单击消息列表中的用户时,数据将通过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 ?我已经工作了好几天了,无法让它工作......

1 个答案:

答案 0 :(得分:0)

您将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 的原始调用可以保持原样,仅使用第一个参数。

相关问题