问题
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