douchuose2514 2017-08-18 14:50
浏览 66
已采纳

AJAX响应和PHP循环

I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.

However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?

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);
}

Also in my PHP, should I be using a while or if statement?

  • 写回答

2条回答 默认 最新

  • dr5779 2017-08-18 14:54
    关注

    You're using a single $data object and resetting its contents each time. You want to build an array of objects:

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

    Followed by:

    success: function(data) {
        $.each(data, function(key, value) {
            $("#transactionTable").prepend(
              '<tr><td>' + value.SerialNo + '</td>' +
              '<td>' + value.CardNo + '</td>' +
              '<td>'+ value.Direction +'</td></tr>');
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿