douchuose2514 2017-08-18 06: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 06: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部