之前博主介绍过一种submit局部刷新的办法,但是单单对于table刷新而去绑定form提交显得太过冗重麻烦,今天介绍下jquery dataTable自带的插件fnReloadAjax实现ajax异步请求刷新表格数据的方法。
前提准备:导入fnReloadAjax.js,附上下载链接
https://pan.baidu.com/s/1qYRMX9i
1、查询按钮
<button onclick="queryStation()">查询button>
2、初始化表格
$("#stationTable").DataTable({
//表格基本配置,根据自己需求设置
"paging" : true,
"lengthChange" : true,
"searching" : false,
"ordering" : false,
"info" : true,
"autoWidth" : false,
"bStateSave" : true,
"bFilter" : true,
"oLanguage" : {
"sUrl" : "plugins/datatables/lang_zh.txt",
},
//刷新数据的重点,请求数据源
ajax : {
//地址
url : "queryStationWithCityCode",
type : "POST",
dataType : "json",
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
error : function(data,e){
alert("系统繁忙,请稍后重试!");
},
//此处不需要写ajax的success回调
},
//请求回数据,对表格列进行赋值(此处每一列都需赋值)
"columns": [
{ "data": "cityName","targets": -1},
{ "data": "townName","targets": -2 },
{ "data": "name","targets": -3 },
{ "data": "address" ,"targets": -4},
{ "data": "contacts","targets":-5 },
{ "data": "phone","targets":-6 },
{ "data": "holidayFlag","targets":-7 },
{ "data": "periodFlag","targets":-8 },
{ "data": "id","targets":-9 },
{ "data": "id","targets":-9 },
],
//自定义列数据
"columnDefs": [
{
"render": function ( data, type,
row ) {
//data为当前列的数据
//type为当前列数据类型
//row为当前行数据
var rowData=JSON.stringify(row);
var str = "联系人";
return str;
//此处return可自己定义,博主此处举例为超链接,传参须注意,若传字符串需加上转义字符,否则会报错ReferenceError: XXX is not defined at HTMLAnchorElement.onclick
},
//此处target负数表示从右向左的顺序
//-1为右侧第一列
"targets": -1
},
{
"render": function ( data, type, row ) {
var str =JSON.stringify(row);
return "删除";
},
"targets": -2
},
],
"createdRow": function ( row, data, index ) {
//创建行之后的操作
},
});
<script type="text/javascript">
//查询
function queryStation(){
var cityCode = $("#sel_town").val();
var parentCode = $("#sel_city").val();
var table = $("#stationTable").dataTable();
//清除表格数据
table.fnClearTable();
//重新请求数据(不写参数代表请求初始化时的默认接口数据)
table.fnReloadAjax("queryStationWithCityCode?cityCode="+cityCode+"&parentCode="+parentCode);
}
script>