Ajax 和 PHP 存在 while 循环问题


Ajax and PHP with a while loop issue

我有一个需要返回一些值的 ajax,但是如果我使用 while() 从我的数据库中获取所有结果,则返回为"无"。我哪里犯了错误?

我的 Ajax 脚本发布在下面:

<script type="text/javascript" charset="utf-8">
  function addmsg(type, msg) {
    var obj = jQuery.parseJSON(msg);
    // Your count variable
    var count = obj.count;
    // Your not variable
    var not = obj.not;
    $('#msg_count').html(count);
    $('#notification').html(not);
  }
  function waitForMsg() {
    $.ajax({
      type: "GET",
      url: "notification/select.php",
      cache: false,
      timeout: 50000,
      success: function(data) {
        addmsg("new", data);
        setTimeout(
          waitForMsg,
          1000
        );
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        addmsg("error", textStatus + " (" + errorThrown + ")");
        setTimeout(
          waitForMsg,
          15000);
      }
    });
  };
  $(document).ready(function() {
    waitForMsg();
  });
</script>

我的 php 脚本发布在下面:

 $result = mysqli_query($con, "SELECT * from notification where tousername='$tousername' and isread = 0");
 while ($row = mysqli_fetch_array($result)) {
     $count = $result - > num_rows;
     $not = $row['notification_msg'];
     $res = [];
     $res['count'] = $count;
     $res['not'] = $not;
 }
 echo json_encode($res);

你在循环中覆盖了结果变量:

while (...) {
  ...
  $res=[];
  ...
}

您可能想要类似以下内容:

$res['count'] = $result->num_rows;
while($row = mysqli_fetch_array($result)) {
  $res[]['not'] = $row['notification_msg'];
}
echo json_encode($res);

使用相同的索引覆盖您的值。 你可以写这个。

while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
$res=[];
$res['count'][] = $count;
$res['not'][] = $not; 
}
Or
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
$res=[];
$res[]['count'] = $count;
$res[]['not'] = $not; 
}
echo json_encode($res);

死();

编写你的 js addmsg()函数。

function addmsg(type, msg) {
    var obj = jQuery.parseJSON(msg);
    // Your count variable
    for(prop in obj){
      var count = obj[prop][count];
      var not = obj[prop][not];
       $('#msg_count').html(count);
       $('#notification').html(not);
    }
  }

重写脚本

function waitForMsg(){
$.get("notification/select.php",function(callback){
console.log(callback); // here is your data in callback variabel you can in in console log
})
}

用你的 php 脚本重新编写此代码。

 $result = mysqli_query($con, "SELECT * from notification where tousername='$tousername' and isread = 0");
       $res['count'] = $result->num_rows;
    while($row = mysqli_fetch_array($result)) {
      $res[]['not'] = $row['notification_msg'];
    }
    echo json_encode($res);