【问题标题】:javascript Setinterval prints repeated data from jsonjavascript Setinterval 打印来自 json 的重复数据
【发布时间】:2015-05-04 06:53:09
【问题描述】:

你好,我有这个代码服务器端来显示在线用户:

header('Content-Type: application/json');
$array = array();
include 'db.php';
$res = mysqli_query($db, "SELECT * FROM `chatters` WHERE status = 1");//users are online
if(mysqli_num_rows($res) > 0){
    while($row = mysqli_fetch_assoc($res)){  
        $array[]= $row;        }
}
echo json_encode($array);

作为回应,我得到了这个:

[{"row_id":"40","name":"Krishan kumar","sex":"male","age":"24","country":"India","seen":"20:58:14", "status": "1"}]

所以我在显示页面上我有这个代码来显示用户:

 $(document).ready(function() {                               
 setInterval(function(){
  $.ajax({
       url: 'json.php',
       dataType: "json",
       type: 'GET',
       success: function(data) {
          if (data) {
            var len = data.length;
            var txt = "";
            for (var i = 0;i<len; i++) {
                txt += "<p>"+data[i].name + "</p>";
            }
            $(".showUsers").append(txt);
            console.log(txt);
          }

       }
    });
  }, 2000);
 });

但问题是每 2 秒我就会打印出这样的名称:

Krishan kumar
Krishan kumar
Krishan kumar
Krishan kumar

它继续.... 我想显示仅打印一次的用户名,同时仍使用setinterval() 打开请求以检查新用户是否在线。如何解决这个问题?

【问题讨论】:

  • $(".showUsers").append(txt);上方添加$('showUsers').empty();
  • 既然来电也应该只打一次,不如用setTimeout
  • 嗨,@Daan 我已经添加了 $('showUsers').empty();上面你说的。但仍然重复这个名字。
  • @saty,我会检查链接。谢谢

标签: javascript php json


【解决方案1】:

请在添加新列表之前清除以前的用户列表。使用以下代码

 setInterval(function(){
 $(".showUsers").html('');
 $.ajax({ ....

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多