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

时间:2014-09-03 01:22:57

标签: javascript php html mongodb

我有一个php文件,它正在触及一个mongo db并构建一堆表标签。当我用PHP代码替换下面的脚本标记代码时,它工作正常并构建表。

当我尝试从被调用页面获取php结果时,我设法将表格文本放入数据变量中...如果我发出警告,我会看到从.php页面生成的所有表格标签和数据。 ..但我不确定如何在HTML标签之后将代码内嵌到HTML中......如果我在脚本中执行document.write(data),它似乎只用数据覆盖整个页面是从.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>

3 个答案:

答案 0 :(得分:2)

我认为脚本标记属于表格之外。 使用tbody thead将帮助您区分静态(标题)和动态(来自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>

答案 1 :(得分:1)

试试这个

        <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>

答案 2 :(得分:0)

您需要使用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>