struts-hibernate-ajax完成区县和街道级联下拉框功能(二补充使用json解析list结果集,ajax循环json层级处理)

针对《struts-hibernate-ajax完成区县和街道级联下拉框功能》进行补充,上一篇中,要在action中拼接JSON格式字符串,很容易手抖。直接用json处理一下转成json格式字符串即可。但之前也讲过,json对于hibernate级联关系的解析,不是很到位啊!

所以ajax那边就得层层循环剥离,找出想要的结果

action:

用的是

import com.alibaba.fastjson.JSON;

具体的jar包请自行百度!!

public String getStreets(){
StreetDao streetDao=new StreetDaoImpl();
try {
streetlist = streetDao.getStreetsByDistrictId(Integer.parseInt(district_id));
/*System.out.println("district_id=="+district_id);
System.out.println(streetlist.size());*/ String content = JSON.toJSONString(streetlist);
/*ObjectMapper mapper = new ObjectMapper();
String content = mapper.writeValueAsString(streetlist);*/
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
response.setCharacterEncoding("utf-8");
System.out.println("array======="+content);
response.getWriter().print(content);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

action只是小小的改动,但语法简单了很多。

出来的json结果是:

array=======[{"district":{"id":1,"name":"天河区","streets":[{"district":{"$ref":"$[0].district"},"id":4,"name":"天河区街道4"},{"district":{"$ref":"$[0].district"},"id":2,"name":"天河区街道2"},{"$ref":"$[0]"},{"district":{"$ref":"$[0].district"},"id":3,"name":"天河区街道3"}]},"id":1,"name":"天河区街道1"},{"$ref":"$[0].district.streets[1]"},{"$ref":"$[0].district.streets[3]"},{"$ref":"$[0].district.streets[0]"}]

看上去真是头疼,即使json格式清晰要想取streets的id和name也不很规律啊,我用了firefox的hj插件JSON-Handle格式化了一下控制台的json字符串

[
{
"district": {
"id": 1,
"name": "天河区",
"streets": [
{
"district": {
"$ref": "$[0].district"
},
"id": 4,
"name": "天河区街道4"
},
{
"district": {
"$ref": "$[0].district"
},
"id": 2,
"name": "天河区街道2"
},
{
"$ref": "$[0]"
},
{
"district": {
"$ref": "$[0].district"
},
"id": 3,
"name": "天河区街道3"
}
]
},
"id": 1,
"name": "天河区街道1"
},
{
"$ref": "$[0].district.streets[1]"
},
{
"$ref": "$[0].district.streets[3]"
},
{
"$ref": "$[0].district.streets[0]"
}
]

那么ajax怎么获取街道呢?

<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#district_id").change(function(){
var district_id = $("#district_id").val();
var url="<%=request.getContextPath()%>/streetlist";
$.ajax({
url:url,
type:'post',
timeout:60000,
data:{"district_id":district_id},
dataType:'json',
success:function(data){
var $street_id = $("#street_id");
var $option =[];
$street_id.empty();
//循环整个json大数组
$.each(data,function(index,item){
//找出第一级的街道ID
if(item.id != '' && item.id !==undefined){
$option.push("<option value='"+item.id+"'>"+item.name+"</option>");
}
//级联关系下的街道ID
$.each(item.district.streets,function(inx,im){
if(im.id!='' &&im.id !==undefined){
$option.push("<option value='"+im.id+"'>"+im.name+"</option>");
}
}); $street_id.append($option);
});
option.push("");
},
error:function(){
alert("查询失败,请联系管理员");
}, });
}); }); </script>

好吧,我也是一点点试的!不行就每一步alert呗!

上一篇:Nodejs使用tedious驱动模块连接SqlServer


下一篇:Codeforces 106 C 多重背包