php - AJAX 响应和 PHP 循环

标签 php jquery mysql ajax

我正在使用 PHP 从 MySQL 数据库中检索一些记录,我想将这些记录发送到我的 AJAX 并循环遍历它们,以便将行 prepend 行添加到现有表中。

但是我只能看到从我的查询返回的最后(最近)记录。有人可以指出我哪里出错了吗?

AJAX:

$.ajax({
    type: "POST",
    url: 'feed.php',
    data: {lastSerial: true},
    dataType: 'json',
    success: function(data){
        console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
        $.each(data, function(key, value) {
            // here I want to loop through the returned results - for example
            $("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
        });
       }
   });

feed.php

if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
  $query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
  // this query returns approx. 20 results
  $stmt = $conn->prepare($query);
  $stmt->execute();
  $result = $stmt->get_result();
  while($row = $result->fetch_assoc()) {
        $data["Direction"] = $row['Direction'];
        $data["CardNo"] =   $row['CardNo'];
        $data["SerialNo"] = $row['SerialNo'];
  }
  echo json_encode($data);
}

同样在我的 PHP 中,我应该使用 while 还是 if 语句?

最佳答案

您正在使用单个 $data 对象并每次都重置其内容。你想构建一个对象数组:

$data = array();

while($row = $result->fetch_assoc()) {
  $data[] = array( 
    "Direction" => $row['Direction'],
    "CardNo"    => $row['CardNo'],
    "SerialNo"  => $row['SerialNo']
  );
}

echo json_encode($data);

其次是:

success: function(data) {
    $.each(data, function(key, value) {
        $("#transactionTable").prepend(
          '<tr><td>' + value.SerialNo + '</td>' +
          '<td>' + value.CardNo + '</td>' +
          '<td>'+ value.Direction +'</td></tr>');
    });
}

关于php - AJAX 响应和 PHP 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45759520/

相关文章:

mysql - CakePHP MySQL虚拟字段问题

php - 301从文件夹重定向到url

php - Laravel 数组到字符串的转换

javascript - 单击一个 div 改变另一个的位置

mysql - 按 2 个月的时间段对出生日期进行分组

mysql - 如何显示 MySQL 中表的唯一约束?

php - Laravel 按年份和月份生成存档帖子

javascript - Base64 图像到 imagecreatefromstring() 丢失数据

Javascript 鼠标悬停事件 Acting Squirrely

javascript - 如何使用 zxing-cpp-emscripten 连续解码 Qr/条形码