首页 > 解决方案 > 在表上附加ajax调用不清除jquery php中的先前数据?

问题描述

我正在使用 jquery 和 php 通过 ajax 调用将动态数据转换为表格格式。我有一个选择选项,我可以选择不同的公司。Onselect 我将使用 ajax 获取特定员工的一些数据,我将该数据绑定到表。但问题是,如果我选择公司 1,那么我可以绑定公司 1 的数据。onchange 公司 1 的公司 2 数据应该消失,公司 2 的数据只存在。但在我的情况下 onchange company 2 以前的数据仍然存在。

下面是我的ajax调用代码:

 $.ajax({

          method: "GET",
           dataType: 'json',
           url:"getdata.php?id="+emp_id,
              success:function (response){
                     $.each(response, function( index, value ) {

                              $("table.table").append("<tr><td>" + response.emp_name + "</td><td>"  + "</td><td><input type='file'></td></tr>");

                      });
              },  
      });

下面是我的html:

<table class="table">
        <thead>
        <tr>
            <th>Employee Name</th>
            <th></th>
        </tr>
        </thead>
        <tbody>

        </tbody>
</table>

标签: phpjqueryajaxappend

解决方案


由于您使用append成功获取数据,因此您必须清除表上的数据,否则它只会在下面添加数据。

在您的 HTML 上

将 attr id 设置为您的<tbody>标签:

 <tbody = "bodytable">

在你的剧本上

添加代码以清除您的数据<tbody>

          $("bodytable").empty();

 $.each(response, function( index, value ) {

      $("table.table").append("<tr><td>" + response.emp_name + "</td><td>"  + "</td><td><input type='file'></td></tr>");

      });

有很多方法可以做到这一点。希望这可以帮助!


推荐阅读