如何使用PHP返回的数据来构建HTML表


How do I use data returned from PHP to build out an HTML table?

我有一个php文件,它正在接触mongodb并构建一堆表标记。当我用php代码替换下面的脚本标记代码时,它可以很好地工作并构建出表。

当我试图从被调用的页面获取php结果时,我设法将表文本获取到数据变量中。。。如果我提醒它,我会看到从我的.php页面生成的所有表标记和数据。。。但我不知道如何在第th个标记之后将代码嵌入HTML中。。。如果我在脚本中执行document.write(数据),它似乎只会用php页面生成的数据覆盖整个页面。。。它不会将它附加在第th行之后。提前谢谢你的建议。

            <table class="table table-striped table-hover">
                 <tr>
                    <th>Agency</th>
                    <th>POC</th> 
                    <th>POC Phone</th>
                    <th>Address</th>
                 </tr>          
                 <script>
                    var data_from_ajax;
                    $.get('build-agency-table.php', function(data) {
                      data_from_ajax = data;
                      alert(data);
                    });
                </script>
            </table>

这是由php脚本返回的

<tr><td>BACODA</td><td>Kristi Smith</td><td>211.444.2222</td>

我认为script标记属于表之外。使用tbodythead将帮助您区分静态(标题)和动态(来自ajax)内容。

 <table>
        <thead>
        <tr>
            <th>Agency</th>
            <th>POC</th> 
            <th>POC Phone</th>
            <th>Address</th>
        </tr> 
        </thead>
        <tbody id="to_fill">
        </tbody>
 </table>

<script>
       var data_from_ajax;
       $.get('build-agency-table.php', function(data) {
         data_from_ajax = data;
         $("#to_fill").html(data_from_ajax);
       });
</script>

试试这个

        <table class="table table-striped table-hover">
             <tr>
                <th>Agency</th>
                <th>POC</th> 
                <th>POC Phone</th>
                <th>Address</th>
             </tr>  
             <tbody id="tablebody"></tbody>
             <script>
                var data_from_ajax;
                $.get('build-agency-table.php', function(data) {
                  data_from_ajax = data;
                  $('#tablebody').html(data);
                  alert(data);
                });
            </script>
        </table>

您需要使用javascript将html内容添加到容器中。

<table>
    <tr>
        <th>...</th>
        <th>...</th>
        <th>...</th>
    </tr>
    <tr id="myRow"></tr>
</table>
<script>       
    $.get('build-agency-table.php', function(data) {
      $("#myRow").html(data); //Add the html content into "myRow"  
    });
</script>