AJAX响应和PHP循环

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?

我使用PHP从MySQL数据库中检索一些记录,我想将这些记录发送到我的AJAX并循环 通过它们,以便将 code>行添加到现有表中。 p>

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

AJAX strong>: p>

  $。ajax({
 type:”POST“,
 url:'feed.php',
 data:{lastSerial:true},
 dataType:'json',
成功:  function(data){
 console.log(data); // logs` {Direction:“O”,CardNo:“02730984”,SerialNo:20559303}`
 $ .each(data,function(key,value)  {
 //这里我想循环返回结果 - 例如
 $(“#transactionTable”)。prepend('&lt; tr&gt;&lt; td&gt;'+ SerialNo +'&lt; / td&gt;&lt;  td&gt;'+ CardNo +'&lt; / td&gt;&lt; td&gt;'+ Direction +'&lt; / td&gt;&lt; / tr&gt;'); 
}); 
} 
}); 
 
nn

feed.php

nn
  if(  isset($ _ POST ['lastSerial'])&amp;&amp; $ _POST ['lastSerial'] == true){
 $ query =“SELECT TimeStamp,Direction,CardNo,SerialNo FROM Transactions”; 
 //此查询 返回约。  20个结果
 $ stmt = $ conn-&gt; prepare($ query); 
 $ stmt-&gt; execute(); 
 $ result = $ stmt-&gt; get_result(); 
 while($ row =  $ result-&gt; fetch_assoc()){
 $ data [“Direction”] = $ row ['Direction']; 
 $ data [“CardNo”] = $ row ['CardNo']; 
 $ data  [“SerialNo”] = $ row ['SerialNo']; 
} 
 echo json_encode($ data); 
} 
  code>  pre> 
 
 

同样在我的PHP中 ,我应该在 code>或 if code>语句时使用吗? p> div>

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

In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.

Many solutions exist, but you have to do something like

$data["Direction"][] = $row['Direction'];
$data["CardNo"][] =   $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];

or better:
$data[] = $row;

Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo

note: not tested