简体   繁体   中英

Table tbody not correctly appending

My table tbody doesn't display the correct data after an AJAX GET request. Well actually, after the second iteration of my for loop, it is showing correctly, but after the third iteration and so on, it is appending but it is showing the previous item.

This is what it showing:

在此处输入图片说明

I don't know why it is showing incorrectly in the table in console log, the data is showing correctly.

$.ajax({
  cache: false,
  type: 'GET',
  url: '@Url.Action("DisplayFiles","FileUploader")', //url, // '/Account/Delete/',        
  dataType: "json",
  success: function(response) {
    $("#tblFiles tbody").remove();

    for (var i = 0; i < response.length; i++) {
      console.log(response[i]['Filename']);
      console.log(response[i]['FileFullPath']);

      $("#tblFiles").append('<tr><td>' + response[i]['Filename'] + '</td><td>' + response[i]['FileFullPath'] + '</td></tr>');

      //var tbodyFiles = "<tr><td> " + response[i]['Filename'] + "</td>" + "<td> " + response[i]['FileFullPath'] + "</td></tr>";
    }

    //$("#tblFiles").append(tbodyFiles);
    console.log(response);
  },
  error: function(resp) {
    console.log('error');
  }
});
<table class="table table-striped" id="tblFiles">
  <thead>
    <tr>
      <th>Filename</th>
      <th>File Fullpath</th>
      @*
      <th>Date Added</th>*@
      <th></th>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in Model) {
    <tr>
      <td>
        @Html.DisplayFor(modelItem => item.Filename)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.FileFullPath)
      </td>
      @*
      <td>
        @Html.DisplayFor(modelItem => item.DateAdded)
      </td>
      *@
      <td>
        @Html.ActionLink(" ", "Delete", new { id = item.Id }, new { @class = "btn-xs btn btn-danger glyphicon glyphicon-trash" })
      </td>
    </tr>
    }
  </tbody>
</table>

Change this:

$("#tblFiles tbody").remove();

to this:

$("#tblFiles tbody tr").remove();

and then change this:

$("#tblFiles").append(...)

to this:

$('#tblFiles tbody").append(...)

Explanation:

You were removing the entire tbody element, but appending the tr s to the table not the tbody .

The proposed changes will ensure that the tbody stays present and that tr s are added as children to it instead of outside of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM