一、剛開始頁面初始化的時候調用該方法,將在頁面顯示初始化記錄頁面如圖
//列表初始化方法進入頁面後調用
$(document).ready(function(){
$.ajax({
url:'init.action',//請求的URL
cache: false, //不從緩存中取數據
data:{pid:2},//發送的參數
type:'Get',//請求類型
dataType:'json',//返回類型是JSON
timeout:20000,//超時
error:function()//出錯處理
{
alert("程序出錯!");
},
success:function(json)//成功處理
{
var len=json.length;//獲得查詢到數組長度
$("<select id='no1' name='querySortId' style='width:80px' onchange='show()'></select>").appendTo("#content");//在content中添加select元素
$("<option value='-1'>請選擇</option>").appendTo("#no1");
for(var i=0;i<len;i++)//把查詢到數據循環添加到select中
{
$("<option value="+json[i].sortId+">"+json[i].sortName+"</option>").appendTo("#no1");
}
}
});
});
當選擇其中一項時觸發onshow()方法,代碼以下:
function show()
{
var obj=event.srcElement;//取得當前事件的對象,也就是你點了哪一個select,這裏獲得的就是那個對象
var currentObj=$(obj);//將JS對象轉換成jQuery對象,這樣才能使用其方法
var s1=$(obj).nextAll("select");//找到當前點擊的後面的select對象
s1.each(function(i){
$(this).remove();//循環把它們刪除
});
var value1=$(obj).val();
$.ajax({
url:'init.action',
cache:false,
data:{pid:value1},
type:'Get',
dataType:'json',
timeout:20000,
error:function()
{
alert("出錯啦");
},
success:function(json)
{
var len=json.length;
if(len!=0)
{
$("<select style='width:80px' name='querySortId' onchange='show()'></select>").appendTo("#content");
for(var i=0;i<len;i++)
{
$("<option value="+json[i].sortId+">"+json[i].sortName+"</option>").appendTo("#content>select:last");
}
}
}
});
}
就會動態的級聯出下一級:界面以下圖:
若是再選擇一樣還會調用onshow()方法,繼續級聯出來,
action中代碼也比較簡單,貼出來供參考一下:
public void init() throws IOException{
HttpServletResponse res=this.getResponse();
HttpServletRequest request=this.getRequest();
res.setContentType("text/html; charset=utf-8");
PrintWriter out;
out = res.getWriter();
String pid=request.getParameter("pid");
int id=Integer.parseInt(pid);
List<TASort> list=sortService.getChildenByConditions(id, "0");//這個查詢全部父親id下面全部的列表
JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter(){
public boolean apply(Object source, String name, Object value) {
if(name.equals("parentSort") || name.equals("TASorts")||name.equals("TAAuths")||name.equals("TBSortInfors")||name.equals("sortInfors")) {
return true;
} else {
return false;
}
}
});
JSONArray arr=JSONArray.fromObject(list,config);//這個類是把list轉換成json的格式
out.print(arr);
}
jsp中代碼以下:
<div id="content" style="width: 500px; border: 1px; border-style: solid; background-color: lightblue;">
</div>
實現以上代碼便可實現無限極聯動。html