layui中ajax的二级联动,中间也出现了一些特殊情况的问题,就是假如一级下拉框不是数组,只有一个元素,后台加了判断,同理,前台也是,计算传入数据的长度用length,后台返回的是数组
前台代码:
//lay-filter=”hospital” 的值。 select()里的参数就是这个 lay-filter是放在select里的一个属性
form.on(‘select(hospital)’, function(data) {
hospital = data.value;
hospitalName = data.elem[data.elem.selectedIndex].text;
// alert(hospital)
.ajax({
type:”POST”,
url:”{:url(‘selectaccount’)}”,
dataType:”json”,
data:{‘hospital’:hospital},
success:function(e){
//empty() 方法从被选元素移除所有内容.ajax({ type:”POST”, url:”{:url(‘selectaccount’)}”, dataType:”json”, data:{‘hospital’:hospital}, success:function(e){ //empty() 方法从被选元素移除所有内容(“select[name=’account’]”).empty();
var html = “请选择账户“;
if(e.length == 1){
html += “” + e[0].name + ““;
}else{
(e).each(function (v, k) {
html += “” + k.name + ““;
});
}
//把遍历的数据放到select表里面(e).each(function (v, k) { html += “” + k.name + ““; }); } //把遍历的数据放到select表里面(“select[name=’account’]”).append(html);
//从新刷新了一下下拉框
form.render(‘select’); //重新渲染
}
})
})
后台代码:
public function selectaccount(){
if(request()->isPost()) {
hospital=input(‘post.hospital′);if(!empty(hospital=input(‘post.hospital′);if(!empty(hospital)){
session(‘hospitalid’,hospital);hospital);hospital_account = explode(“,”, session(‘hospital_id’));
foreach(hospitalaccountashospitalaccountasval){
hospitalids=explode("′′,hospitalids=explode("",val);
if(hospital==hospital==hospital_ids[0])
accountids[]=accountids[]=hospital_ids[1];
}
}
if(count(accountids)>1)$account=db(′semaccount′)−>where(′id′,′in′,$accountids)−>select();else$account=db(′semaccount′)−>where(′id′,$accountids[0])−>select();returnaccountids)>1)$account=db(′semaccount′)−>where(′id′,′in′,$accountids)−>select();else$account=db(′semaccount′)−>where(′id′,$accountids[0])−>select();returnaccount;
}
}