渲染AJAX结果时如何避免闪烁?

时间:2018-04-01 16:28:02

标签: javascript dom

我已经建立了一个聊天,我希望div #pm中的消息能够自动刷新,直到我找到这个代码:

<script>
function chat_ajax(){
  var req = new XMLHttpRequest();
  req.onreadystatechange = function()
  {
     if(req.readyState == 4 && req.status == 200)
     {
        document.getElementById('pm').innerHTML = req.responseText;
      }
    }
    req.open('GET', 'getpm.php', true);
    req.send();
  } setInterval(function(){chat_ajax()}, 2000)
</script>

它运行良好,但它一直闪烁,这很烦人。我认为那是因为它刷新整个HTML,我不确切知道,有人用JSON告诉我你可以做到并摆脱闪烁。我怎么能完成它?

这个getpm.php

  while ($msg_row = mysqli_fetch_array($msg_sql_result))
    {
      $user_pm = $msg_row['USER_NAME'];
      $user_id = $msg_row['USER_ID'];

      $check_admin = "SELECT * FROM users WHERE ID='{$user_id}'";
      $check_admin_result = mysqli_query($connection , $check_admin);
      $fetch_admin = mysqli_fetch_array($check_admin_result);
      $userID = $fetch_admin['ID'];

                    if ($fetch_admin['Admin'] == 1)
                    {
                      ?>
                      <div class="pm_msg" style="word-wrap:break-word;">
                      <img style="width:17px" src="img/crown.gif" />
                      <span style="font-weight:bold;">
                      <a style="text-decoration:none;color:#<?php echo $fetch_admin['NICK_RGB'];?>;" href="user_profile.php?ID=<?php echo urlencode($fetch_admin['ID']);?>">
                      <?php echo $fetch_admin['Username']." : "?></a>
                      </span>
                      <span style="color:#<?php echo $fetch_admin['TEXT_RGB'];?>;">
                      <?php echo $msg_row['TXT']."<br>";?></span>
                      </div>
                      <?php
                      // $rating = $fetch_admin['RATING'];
                      // $rating++;
                      // $rating_sql = "UPDATE users SET RATING='{$rating}' WHERE Username='{$user_pm}'";
                      // $rating_sql_result = mysqli_query($connection,$rating_sql);
                    }

0 个答案:

没有答案