jquery用ajax实现级联



jquery用ajax实现级联.

标签: jqueryajax级联

 

1、刚开始页面初始化的时候调用该方法,将在页面显示初始化记录页面如图

//列表初始化方法进入页面后调用

$(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>

实现以上代码即可实现无限极联动。

http://www.oecp.cn/hi/chengzhengliang/blog/1962