【问题标题】:How to echo <tr> using php and ajax to appear inside <table> </table>如何使用 php 和 ajax 回显 <tr> 以出现在 <table> </table> 中
【发布时间】:2015-02-10 21:59:48
【问题描述】:

我目前正在学习 ajax 和 php。我想要做的是从 php 文件中回显表行。这是我的代码。

HTML 代码:

<table  class = "table table-hover table-striped">
    <tr>
        <th>Product ID</th>
        <th>Product Name</th> 
        <th>Price</th> 
        <th>Terms</th>
    </tr>

<-- I want the new table row to appear here -->

</table>

PHP 代码

<?php
    $x = 10;

    while($x > 0)
    {

        echo '<tr>
                    <td>'.$x.'</td>
                    <td>'.$x.' Name</td> 
                    <td>'.$x.' Pesos</td> 
                    <td>'.$x.' Years</td>
           </tr>';

        $x--;
    }
?>

Ajax 脚本

<script>
function showDetails()
{
     var xmlhttp;

     if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
         if (xmlhttp.readyState==4 &&     xmlhttp.status==200)
         {
          document.getElementById("myNewTableRow").innerHTML=xmlhttp.responseText;
         }
    }
      xmlhttp.open("POST","sample-php-ajax.php",true);
      xmlhttp.send();
    }
</script>

在哪里放置 ID 以便在我使用 ajax 调用 php 文件时显示它想要回显的内容?

【问题讨论】:

  • 你的 ajax 代码在哪里?
  • 我在这里没有看到任何关于 ajax 的代码。
  • 我很抱歉没有为 ajax 添加脚本。我已经对其进行了编辑,感谢您抽出宝贵时间阅读。

标签: php html ajax


【解决方案1】:

在表格中,您可以使用例如如果使用 jQuery。

 $('#tableid').append($yourtr);

我还会将您的标题放在&lt;thead&gt; 标记中,以便在您稍后排序时保持在顶部。

没有jQuery你可以使用

 document.getElementById('tableid').appendChild(yourtr);

【讨论】:

  • 他没有使用 jQuery,他的 Ajax 代码不是很清楚吗...?
  • 我开始写答案后添加了ajax代码,但是你可以用普通js做同样的事情
  • 对此我深表歉意,我忘记为 ajax 添加脚本
  • 更改您的答案以使用 javascript :)
【解决方案2】:

您可以使用以下代码

<table id="result" class = "table table-hover able-striped"> // add ID here

在ajax中获取数据并将其附加到表中

document.getElementById("result").appedChild(xmlhttp.responseText)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多