我正在尝试进行基于Ajax的搜索,但我在javascript和ajax中非常新。我需要对结果进行排序,过滤等,因此我将结果放入Datatables。 首先,我使用标准的html表单输入(它是主要的搜索字段):
<input type="text" class="form-control" formmethod="post" oninput="return delayExecute();" id="name" name="name" size="61" autofocus/>
当用户将某些内容放入表单时,它会调用delayExecute()函数。接下来,用户完成脚本运行ajax请求后一秒钟。脚本看起来像这样:
<script>
var typingTimer;
var doneTypingInterval = 700;
function delayExecute()
{
clearTimeout(typingTimer);
typingTimer = setTimeout(
function(){makeAjaxRequest(name)},
1000
);
return true;
}
function makeAjaxRequest(name) {
$('#loading')
.show()
var myrequest = $.ajax({
url: 'ajax_search',
type: 'post',
data: {name: $('input#name').val()},
ajaxSend: function() {
},
success: function(response) {
$('table#dataTables-example tbody').html(response);
},
complete:function(){
//
$('#loading')
.hide();
$('#dataTables-example').dataTable({
// "destroy": true,
"processing": true,
"aaSorting": [],
"iDisplayLength": 10,
"aLengthMenu":[[10, 15, 25, 35, 50, 100, -1], [10, 15, 25, 35, 50, 100, "All"]]
}).columnFilter(
{
aoColumns: [
{type: "null"},
{sSelector: "#mag_filter_column", type: "select"},
]
}
);
}
});
};
在Php文件(ajax_request)中,我从数据库中读取数据。接下来,我使用echo函数将事物放入表中:
echo '<tr>';
echo '<td>'.$some_variable.'</td>';
echo '<td>'.$other_variable.'</td>';
echo '</tr>;
视图中的表格如下:
<table class="main-search table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Col</th>
<th>War</th>
<th>Symbol</th>
<th>Name</th>
<th>Quantity</th>
<th>Descripion</th>
<th>Photo</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
这一切几乎都有效。当我第一次进行搜索时,它将所有内容加载到数据表中,一切正常(分页,排序等)。但是当我进行第二次搜索(例如更改某些单词) - ajax serch运行时,它会找到一些东西,但数据不会加载到数据表中。我认为我需要找到刷新数据库插件的方法。我试图使用datatable.clear(),datatable.destroy()并结合其他东西,但没有什么对我有用。什么是正确的方法?
我的数据表插件版本:DataTables 1.10.5
jquery版本:2.1.1