2016-09-04 18 views
0

我对php和javascript(ajax)仍然很陌生,并且我尝试过查看各种帖子和试图查找的网站我的答案,但无济于事。从数据库(SQL)使用php/javascript(ajax)向网站前端显示多行

我想从我的数据库中的网站的前端显示所有相关的行。我的SQL语句正在拾取我需要的所有行,但我无法显示所有行(我只能得到一行显示)。

有人可以指导我一下,并告诉我该怎么做才能正确吗?我的代码如下:

PHP的

$result = mysql_query("SELECT lot_num, buyer_id, item_desc, quantity, price FROM auction_items where auction_id = (SELECT id FROM auction ORDER BY date_created desc Limit 1) ORDER BY id DESC");   //query 

    $table_data = array(); 
    while($row = mysql_fetch_array($result)){ 
     $table_data[]= (array('lot_num' => $row["lot_num"], 'buyer_id' => $row["buyer_id"], 'item_desc' => $row["item_desc"], 'quantity' => $row["quantity"], 'price' => $row["price"])); 
    } 
    // $array = mysql_fetch_row($result);  

    echo json_encode($table_data); 

我也将包括我的JavaScript(AJAX)的代码覆盖我的基地:

$("#submit").click(function(){ 
    $.ajax({          
     url: 'auctionItemLoad.php',  //the script to call to get data   
     dataType: 'json',    //data format  
     success: function(data)   //on recieve of reply 
     { 
      var lot_num = data[0];    
      var buyer_id = data[1];   
      var item_desc = data[2]; 
      var quantity = data[3]; 
      var price = data[4]; 
      $('#lot_num_result').html(lot_num); 
      $('#buyer_id_result').html(buyer_id); 
      $('#item_desc_result').html(item_desc); 
      $('#quantity_result').html(quantity); 
      $('#price_result').html(price); 
     } 
     }); 
    }); 
+0

console.log(data)在控制台中显示的内容是什么,如果你输入它而不是var lot-.num = ...和整个东西?成功:功能(数据) { console.log(data); } –

+0

好吧,在我加入Nich的加入之后,它现在显示了我在数据库中的所有对象。 –

回答

0

的原因只有一个行显示是因为您只访问数据的第一行,您必须遍历所有行以显示其所有数据。就像你迭代PHP文件中的所有sql请求的结果行以将它们添加到$table_data阵列一样,你必须在你的ajax请求的成功回调中迭代data,这次输出数据。你可以用JQuery的每个函数来做到这一点。

... 
success: function(data) { 
    $.each(data, function(i, row) { 
     var lot_num = row.lot_num;    
     var buyer_id = row.buyer_id;   
     var item_desc = row.item_desc; 
     var quantity = row.quantity; 
     var price = row.price; 

     $('#lot_num_result').append(lot_num); 
     $('#buyer_id_result').append(buyer_id); 
     $('#item_desc_result').append(item_desc); 
     $('#quantity_result').append(quantity); 
     $('#price_result').append(price); 
    )}; 
} 
... 
+0

这似乎是向我展示了一切,但它都在一条线上。我将如何去分解信息,以便在遍历一行(或变量)后,它会进入下一行? –

+0

@PACIFIC_STATE如果id选择器('#lot_num_result','#buyer_id_result'等)是列,为了简化示例,我会将它们中的每个项目添加到'div'中的不同行上。而不是做'$('#lot_num_result')。append(lot_num);',我会做'$('#lot_num_result')。append('

' + lot_num + '
');'这可能不是你正在寻找的虽然。 这个动态创建表的解决方案可能更有用:http://stackoverflow.com/a/8302187/5709703 – nich

+1

非常感谢。你一直是一个很大的帮助! –

相关问题