How to clear previous search result shown by ajax success?

旧时模样 提交于 2019-12-11 16:07:21

问题


I wanted to clear all the search result shown by ajax search like when the user type for next query it will update it.

 $(document).ready(function(){
    var text;
    $("#button").on('click',function (e) {
    e.preventDefault();
   var q=$("#q").val();
    $.ajax({

    url: "/search",
    data:  {q:q},
    type: "GET", 
    dataType : "json",
    success: function(result) { 
    var event_data = '';
    for (var i = 0; i < result.length; i++) {
                event_data += '<tr>';
                event_data += '<td>' + '<img src=' +result[i]['video']['thumbnail_src']+ '></img>' +'</td>';
                event_data += '<td>' +result[i]['video']['title']+'</td>';
                event_data += '<td>' +result[i]['video']['duration']+ '</td>';
                event_data += '<td>' + '<a href' +result[i]['video']['url']+ '>'+ "Download" +'</a>' +'</td>';
                event_data += '</tr>';
     }  $("#list_table_json").append(event_data);
    },
    error: function(jqxhr, status, exception) {
             alert('Exception:', exception);
         },
    always: function( xhr, status ) {
      alert( "The request is complete!" );
        }
    });
});


   });

This is my html file for table where i was appending result from ajax success, can you guys let me know another technique for this. I wanted to clear previous result and update the new result.

Search
<table class="table table-responsive table-hover table-bordered" id="list_table_json">
<thead>
    <tr>
        <th>Thumbnail</th>
        <th>Title</th>
        <th>Duration</th>    
        <th>Download</th>                
    </tr>                   
</thead>


回答1:


On the start of the success handler, use the below code if you want to keep the first tr (headings) and remove the rest of the data

$("#list_table_json").find("tr:gt(0)").remove();

or use if you want to remove everything

$("#list_table_json").empty(); 

or another way to remove everything

$("#list_table_json").html('');

How to use?

success: function(result) { 
    $("#list_table_json").find("tr:gt(0)").remove();
    var event_data = '';


来源:https://stackoverflow.com/questions/56881703/how-to-clear-previous-search-result-shown-by-ajax-success

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!