我有这个Ajax调用,用数据填充表。但是,当我再次进行相同的调用时,它会加载新旧数据。如何在加载新数据之前清除旧数据?
$(function() {
$('#subject_search_btn').click(function() {
var student_id = $('#search').val();
var year = $('#year').val();
var term = $('#term').val();
var classs = $('#formclass').val();
$.ajax({
"url": "/search_student_results",
"data": {"studentid":student_id, "year":year, "term":term, "formclass":classs},
"type": "get",
"dataType": "json",
"success": function(data) {
if (data.length == 0){
alert(year+' '+'Term'+' '+term+' '+'Results not found');
}
else
var trHTML = '';
$.each(data, function (i, item) {
trHTML += '<tr>' +
'<td>' + item.subject.name + '</td>' +
'<td>' + item.score + '</td>' +
'<td>' + item.position + '</td>' +
'<td>' + item.remark + '</td>' +
'</tr>';
});
$('#subject_tbody').append(trHTML);
},
"error": function() {
alert(year+' '+'Term'+' '+term+' '+'Results not found');
}
});
});
});
我没有成功尝试
var subject_score = $('.subjectscore').filter(function() {
subject_score.empty();
或:
var subject_score = $('.subjectscore').filter(function() {
subject_score.parent().parent().remove();
请帮忙解决这个问题。
答案 0 :(得分:0)
更新:
它将删除表的内容,添加你的cleardata,然后你的ajax收到数据。
$(function() {
$('#subject_search_btn').click(function() {
var student_id = $('#search').val();
var year = $('#year').val();
var term = $('#term').val();
var classs = $('#formclass').val();
$.ajax({
"url": "/search_student_results",
"data": {"studentid":student_id, "year":year, "term":term, "formclass":classs},
"type": "get",
"dataType": "json",
"success": function(data) {
if (data.length == 0){
alert(year+' '+'Term'+' '+term+' '+'Results not found');
}
else
{
$('#subject_tbody').empty();
var clearHTML = '<tr> <td class="cleardata"></td> <td class="cleardata"></td> <td class="cleardata"></td> <td class="cleardata"></td> </tr>';
var trHTML = '';
$.each(data, function (i, item) {
trHTML += '<tr>' +
'<td>' + item.subject.name + '</td>' +
'<td>' + item.score + '</td>' +
'<td>' + item.position + '</td>' +
'<td>' + item.remark + '</td>' +
'</tr>';
});
$('#subject_tbody').append(clearHTML);
$('#subject_tbody').append(trHTML);
}
},
"error": function() {
alert(year+' '+'Term'+' '+term+' '+'Results not found');
}
});
});
});
答案 1 :(得分:0)
改为使用.html(html)函数:
$('#subject_tbody').html(trHTML);
或者在追加之前先清除内容:
$('#subject_tbody').html('').append(trHTML);
答案 2 :(得分:0)
clearconsole();功能可以帮助
$(document).on("click", ".class, function(e) {
$.ajax({
dataType: 'json',
url: "/ajax/getData.php",
type: "POST",
success: function(data){
},error: function(){
});
clearconsole();
});
这在您使用load()时有效;与具有和ajax代码的页面。每次您加载()时,ajax似乎都会执行;页面而不刷新浏览器