上班太无聊,分享一点自己做项目的心得,前几天接到这样的需求,苦于很多帖子都难看懂,无赖只好自己研究,现把
我的经验分享给大家,免得大家走弯路,。
需求:
1.Call4bid和Allocation一对多关系,需要列出(下拉框)一个Call4bid的所有Allocation;
2.依赖Google,gson-1.6.jar。
2.页面代码
1.当然页面上首先是列出来了当前年所有的CALL4BID的,是一个下拉框,然后选择的时候有一个出发事件(change)通过AJAX的POST提交到后端把所有的CALL4BID查出来。(就是前台的那个suggest)。
(1) 假定有一个ID为select的下拉框
<select style="width: 304px;" name="year" id="select">
<c:forEach items="${yearList}" var="var">
<option value="${var }">${var}</option>
</c:forEach>
</select>
(2)网页里面有一个ID是SP的DIV ,里面有2个UL,每个UL里面有N个LI,前面的UL用于显示CALL4BID名称,后面的
UL用来用来显示所有的Allocation(下拉框)
<div id="sp">
<ul class="newname">
<li></li>
</ul>
<ul class="newinput">
<li>
</li>
</ul>
</div>
(2)Jquery代码(代码很长,估计很难看懂list封装厂JSON对象后传到页面成了一个字符串数组)
<script type="text/javascript">
$(document).ready(function(){
$("#select").change(function(){
txt=$("#select").val(); //获取CALL4BID那个下拉框的值
$.post("fd/ajax.htm",{suggest:txt},function(result){
$("#sp").html(""); //jquery的POST的方法,前面的(fd/ajax.htm)是请求路径,(suggest)是后台
接收的参数,(result)是后端返回过来的数据,这里是一个JSON对象.
var group1 = $("<ul class=\"newname\"></ul>");
//循环这个JSON对象,外层循环拿出来的是所有的CALL4BID (result[i].name 拿出NAME属性的值)
$.each(result,function(i){
group1.append("<li>"+result[i].name+":"+"</li>");
});
//下面是2层循环,拿出一个CALL4BID所有的Allocation
var group2 = $("<ul class=\"newinput\"></ul>");
$.each(result,function(i){
var ligroup = $("<li></li>");
var select2 = $("<select style=\"width: 320px;\" name=\"allocationid\" id=\"select\"> </select>");
$.each(result[i].allocations,function(j){
select2.append("<option value='"+result[i].allocations[j].id+"'>"+result[i].allocations[j].name+"</option>");
})
select2.append("<option value='0'>None</option>");
ligroup.append(select2);
group2.append(ligroup);
});
$("#sp").append(group1).append(group2);
$(parent.document).find('iframe').height($(".content").height()+31);
});
});
});
</script>
上面太难看懂了。我写个精简版的,至于构造页面自己append就行(实际情况而定)
<script type="text/javascript">
$(document).ready(function(){
$("#select").change(function(){
txt=$("#select").val();
$.post("fd/ajax.htm",{suggest:txt},function(result){
$("#sp").html("");
//这个循环可以拿出所有的CALL4BID
$.each(result,function(i){
result[i].name
});
// 这个2层循环可以遍历出一个CALL4BID的所有的Allocation
$.each(result,function(i){
$.each(result[i].allocations,function(j){
result[i].allocations[j].name
});
</script>