添加<tr>元素到动态表,动态不刷新页面,php-jquery

Add a <tr> element to dynamic table, dynamically without a page refresh, php jquery

本文关键字:动态 刷新 php-jquery tr lt gt 元素 添加      更新时间:2023-10-30

我正试图在单击按钮时向现有表中添加一个动态行,该行是使用PHP脚本的输出动态创建的。

我对脚本insert_tr.php进行了ajax调用,它以与包含数据的现有表相同的格式向我返回一个TR元素。适当地返回数据

但不幸的是,<tr>行并没有动态添加到表中,而是仅在页面刷新后添加。

PHP文件代码:

   <div id="v_div">
    <table class="table table-bordered table-striped" >
     <thead>
        <th class='col-md-2'>name</th>
            <th class='col-md-2'>number</th>
     </thead>
     <tbody>
    <?php  
            while ($data = pg_fetch_assoc($ret)) {
              echo 
              "<tr id=tr_".$data['sr_number'].">
                <td class='td_topic' id=title:".$data['number']." >".trim($data['name'])."</td>
                <td class='td_topic' id=title:".$data['number']." >".trim($data['number'])."</td>
            <td class='td_topic' id=title:".$data['number']." ><button class='btn btn-info check1' type=button title='Add Entry'>Add Entry</button></td>
          </tr>";
    ?> 
       </tbody>
    </table>
    </div>

Javascript:

$(document).ready(function() {
  $("#v_div").on('click', '.check1', function() {
    var field_userid = $(this).parent().attr("id");
    var value = $(this).text();
    $.post('insert_tr.php', field_userid + "=" + value, function(data) {
      if (data != '') {
        $(this).closest("tr").after(data);
      }
    });
  });
});

我所想做的就是在当前TR打开后立即添加行,动态地添加行而不刷新页面,这为ajax调用的最终用途提供了服务。

this的引用不是单击的按钮。

$(this).closest("tr").after(data);

存储对Ajax调用外部行的引用。

$(document).ready(function() {
  $("#v_div").on('click', '.check1', function() {
    var field_userid = $(this).parent().attr("id");
    var value = $(this).text();
    var row = $(this).closest("tr");
    $.post('insert_tr.php', field_userid + "=" + value, function(data) {
      if (data != '') {
        row.after(data);
      }
    });
  });
});