先看一下效果
加载列表要根据数据库进行反显。选择上一级,下一级需要初始化。
首先说一下设计页面是有缺陷的。5级联动都要进行数据库查询的,因为是分页列表,即使分页是10条,那么这一个页面的查询数据库次数也是50个。这对数据库来说是很大的负担。
如何实现
第一个就是field,以小区为例,这块formatter,自定义一个函数,函数中拼接select即可。还有一个是event事件,对应了change事件,change事件中初始化楼号、单元、户室并获取楼号。
getXqList里面就是有2层逻辑,如果有sqId,说明是社区改变了,然后初始化小区列表。如果sqId是null,就是根据数据库内容进行反显。
ajax都是同步的,异步的话加载不出来数据。
{
field : 'xq',
title : '小区',
formatter:function (value, row, index) {
return getXqList(value, row, index);
},
events: {
'change .xqSelect': function (e, value, row, index) {
//获取当前选中的值
var selectedValue = $(this).children('option:selected').val();
$("#lhSelect" + row.id).html("");
$("#dySelect" + row.id).html("");
$("#hsSelect" + row.id).html("");
getLhList(value, row, index, selectedValue);
}
}
},
function getXqList(value,row,index, sqId) {
if(sqId) {
var str = '<option value="">请选择</option>';
$.ajax({
url : prefix+"/getXqBySqId",
type : "post",
data : {
'sqId' : sqId,
},
async: false,
success : function(r) {
if (r.code==0) {
r.data.forEach(function (val, ind, arr) {
if(ind === 0) {
getLhList(value, row, index, val);
}
str += '<option value="'+val+'">' +val+ '</option>';
});
}else{
layer.msg(r.msg);
}
}
});
$("#xqSelect" + row.id).append(str);
} else {
var str = '';
sqId = row.sqId;
if(!sqId) {
str = '<select style="width: 100%" id="xqSelect' + row.id + '" name="xqSelect' + row.id + '" class = "xqSelect"><option value="">请选择</option></select>';
}
var xqStr = sessionStorage.getItem(sqId);
if(xqStr) {
xqList = xqStr.split(',');
str = '<select style="width: 100%" id="xqSelect' + row.id + '" name="xqSelect' + row.id + '" class = "xqSelect">';
str += '<option value="">请选择</option>';
xqList.forEach(function (val, ind, arr) {
if(!row.xq && ind === 0) {
row.xq = val;
}
if(row.xq === val) {
str += '<option value="'+val+'" selected>' +val+ '</option>';
} else {
str += '<option value="'+val+'">' +val+ '</option>';
}
});
str += '</select>';
} else {
$.ajax({
url : prefix+"/getXqBySqId",
type : "post",
data : {
'sqId' : sqId,
},
async: false,
success : function(r) {
if (r.code==0) {
sessionStorage.setItem(sqId, r.data);
str = '<select style="width: 100%" id="xqSelect' + row.id + '" name="xqSelect' + row.id + '" class = "xqSelect">';
str += '<option value="">请选择</option>';
r.data.forEach(function (val, ind, arr) {
if(!row.xq && ind === 0) {
row.xq = val;
}
if(row.xq === val) {
str += '<option value="'+val+'" selected>' +val+ '</option>';
} else {
str += '<option value="'+val+'">' +val+ '</option>';
}
});
str += '</select>';
}else{
layer.msg(r.msg);
}
}
});
}
return str;
}
}
其他的select同理。
至于由于设计导致的加载时间长如何优化,我做了2方面改进:
1、后台也是有几十万数据,加索引。
2、前端使用缓存。sessionStorage。