Jquery数据表字符串过滤器
问题描述:
下面的代码工作得很好,并获取所有的数据。我想在数据表中插入一些过滤器字符串(sample_container)。因此,对于给定的sample_app,想要在加载页面时自动使用某些过滤器字符串(filter1,filter2)为sample_container数据表进行过滤。有任何想法吗?Jquery数据表字符串过滤器
$("#sample_container").html("<h2>Sample libs</h2>");
$.ajax({
type: "GET",
url: "some_url",
data: some_data,
dataType: 'jsonp',
crossDomain: true,
async: false,
success: function(response) {
$("#sample_container").html("<h2>Sample Libraries</h2>");
html = "<table class='datatable'>";
blah blah
}
html += "</table>";
$("#sample_container").append(html);
$("#sample_container .datatable").dataTable({ "bPaginate": false,
"bAutoWidth": false,
"bFilter": false,
"bInfo": false
}).columnFilter({ sPlaceHolder: "head:after",
aoColumns: [ { type: "text" },
{ type: "text" },
{ type: "text" }
]
});
},
});
{% if sample_app %}
<h1>{{ sample_app.id }} - {{ sample_app.name }}</h1>
<br/>
blah blah...
{% endif %}
答
不仅速度更快,而且更直接地做一个服务器端的DataTables实现。从本质上讲,你正在绘制一个完整的表格,然后完全重写......这是非常低效的,并且在变得笨重之前可能无法处理超过几百行的数据。
数据表,通过 “服务器端” 进行查询:
$('#marketinghistory').dataTable({
"bDestroy":true,
"aaSorting": [[ 0, "desc" ]],
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "url of ajax source",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bAutoWidth": false,
"bFilter":false,
"bLengthChange": true,
"bPaginate": true,
"bSort": true,
"iDisplayLength": 15,
"bInfo": true,
"aoColumns": [
{ "sTitle": "column title", "sWidth": "5%", "sClass":"center" },
{ "sTitle": "column title", "sWidth": "25%" , "sClass":"center"},
{ "sTitle": "column title", "sWidth": "10%", "sClass":"center" },
{ "sTitle": "column title", "sWidth": "5%", "sClass":"center" }
]
});
现在,过滤,你有几种选择。如果您事先知道要做什么,可以将它们作为变量传递给“数据”字段,然后在服务器上进行排序。但是,你可能希望它是可变的......在这种情况下,还有更多的箍筋。上述
添加此代码块到数据表的代码会允许你做变量过滤器:
"fnServerData": function (sSource, aoData, fnCallback) {
var name = $('#namesearch').val();
var phone = $('#phonesearch').val();
var company = $('#companysearch').val();
aoData.push({ "name": "name", "value": name },
{ "name": "phone", "value": phone },
{ "name": "company", "value": company }
);
$.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
因此,变量设置为输入字段的值可用于过滤器的基础上的网页上用户输入。 aodata.push设置数据以推回回调,并且ajax回调完成这项工作。我在高级搜索页面上使用这种模式,搜索字段在左侧,数据表在右侧。最初,空白字段没有搜索过滤器,但随着值被填充并且表格被重新绘制,服务器可以过滤查询。
当然,这需要相当直接的后端设置来方便查询。 A tut on that is here。