在表格中显示ajax响应

时间:2017-07-04 18:37:20

标签: javascript php jquery ajax

我想在表格中显示来自ajax响应的数据。

这是我的表:

<table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table">
    <thead>
    <tr>
        <th class="centerText" data-field="item_id">ID</th>
        <th class="centerText" data-field="name">Name</th>
        <th class="centerText" data-field="price">Price</th>
        <th class="centerText" data-field="image">Image</th>
        <th class="centerText" data-field="edit">Edit</th>
    </tr>
    </thead>
    <tbody style="text-align:center;" id="menu_table_data"></tbody>
</table>

这是 menu_table.php ,它从数据库获取数据并将响应返回给ajax:

$output = '';
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;");

while($data = mysqli_fetch_array($search))
{
    $output .= '<td>'.$data['id'].'</td>
                <td>'.$data['name'].'</td>
                <td>'.$data['price'].'</td>
                <td><div id="div_image">
                <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div></td>
                <td><a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a></td>
                ';
}
echo $output;

这是ajax功能:

$(document).ready(function(){
    function fetch_data(){
        $.ajax({
            url: "menu_table.php",
            method: "POST",
            success: function(data){
                $('#menu_table_data').html(data);
            }
        });
    }
    fetch_data();
});

$('#menu_table_data')。html(数据); 显示的是数据但不像表数据。如何在桌子内正确显示?

1 个答案:

答案 0 :(得分:3)

您错过了<tr></tr>

试试这个:

$output = ''; 
$search = mysqli_query($link,"SELECT menu.id, menu.name, menu.price, menu.image ORDER BY menu.id ASC;"); 
while($data = mysqli_fetch_array($search)) { 
    $output .= '
    <tr>
      <td>'.$data['id'].'</td>
      <td>'.$data['name'].'</td>
      <td>'.$data['price'].'</td>
      <td>
        <div id="div_image">
          <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div>
      </td>
      <td>
        <a class="btn btn-primary glyphicon glyphicon-edit" role="button"></a>
      </td>
    </tr>
    '; 
}
echo $output;