【发布时间】:2017-08-29 18:18:05
【问题描述】:
我有三个表,我使用选择列表元素显示每个表,并使用 ajax 和 jquery 来返回表。我希望每当我从列表中选择一个新表时,ajax 应该只为我带来该表中的数据。
这是我的表格:
<div class="panel">
<div class="panel-heading">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Term</span>
<!-- I passed the tables name as values for a specific period -->
<select name="term" class="form-control" id="term">
<option value="">Select Period</option>
<option value="period_one">1st Period</option>
<option value="period_two">2nd Period</option>
</select>
</div>
</div>
<div class="panel-body">
<table class="table table-responsive table-bordered table-condensed table-striped table-hover" id="dataTable">
<thead>
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Class</th>
<th>Score</th>
</tr>
</thead>
<tbody id="periodTable">
</tbody>
</table>
</div>
</div>
Ajax 带来了预期的结果,但是我添加的 dataTables 插件在 ajax 调用上有点不刷新。例如,如果我选择“第一个周期”,它会返回“第一个周期”的表,其中有两 (2) 行“狗和猫”。 dataTables 告诉我 显示 2 个条目中的 1 到 10 个,这是正确的。但是,如果我选择 '2nd Period' ajax 会返回期望的结果,但 dataTables 仍然显示 Showing 1 to 10 of 2 entries 即使'2nd Period' 有更少或更多。
此外,如果在下一张表上进行搜索,则它不会按预期工作。以下是我编写脚本的方式:
$(document).ready(function() {
$('#term').on('change', function() {
var term = $('#term').val();
if (term != '') {
$.ajax({
url:"findGrades.php",
type:"post",
data:{"term":term},
dataType:"json",
success:function(data){
// clearing the table so that only result from the next table are shown. To do this I got help from this thread:
//http://stackoverflow.com/questions/43206680/new-ajax-request-on-drop-down-selection
$("#periodTable").replaceWith('<tbody id="periodTable"></tbody>');
for (var count = 0; count < data.length; count++) {
var htmlData = '<tr><td data-type="text" data-name="student_name" data-pk="'+data[count].id+'" class="student_name">'+data[count].first_name+' '+data[count].middle_name+' '+data[count].surname+'</td>';
htmlData += '<td data-type="text" data-name="subject_name" data-pk="'+data[count].id+'" class="subject_name">'+data[count].subject_name+'</td>';
htmlData += '<td data-type="text" data-name="class_name" data-pk="'+data[count].id+'" class="class_name">'+data[count].class_name+'</td>';
if (data[count].score <= 69 ) {
htmlData += '<td style="color:red;" data-type="text" data-name="score" data-pk="'+data[count].id+'" class="score">'+data[count].score+'</td></tr>';
} else {
htmlData += '<td data-type="text" data-name="score" data-pk="'+data[count].id+'" class="score">'+data[count].score+'</td></tr>';
}
$("#periodTable").append(htmlData);
}
// calling the data table function after data have been return by ajax
$('#dataTable').DataTable();
}
});
} else {
$('#periodTable').html('');
}
});
});
【问题讨论】:
标签: javascript php jquery ajax datatable