日期:2014-05-16  浏览次数:20311 次

Json配合Jquery在struct2中的应用
1.我在做项目的时候页面上的一个select要动态的加载出来,想到用Jquery做比较方便些》
至于前面的javaBean,ibatis操作数据库,dao层,spring层这里就不说了,抓关键点说说
恩,我这里是在struts2中处理的:
首先处理传递的数据是json的格式的:
public String queryDepartAlldname(){
//查询后台得到的是个list对象
List<Department> departments=departservices.queryDepartAll();
//手动拼json开始
String json = "";
                  //定义号json的格式
String format = "{did:%d, dname: '%s'}";
//从list中循环取值放入到json
for(int i = 0; i < departments.size(); i ++){
json += String.format(format, departments.get(i).getDid(),
departments.get(i).getDname());
if(i < departments.size() - 1){
json += ",";
}
}

json = "[" + json + "]";

                  //获得respsonse对象
ActionContext ctx=ActionContext.getContext();
  HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);       
  try {
 
//将json在response中打印出来,json都是这样做的
response.getWriter().print(json);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}          //这里不要返回的
  return null;
}




2.在页面的处理:
很简单写个js用Jquery做,注意页面要导入Jquery的js
<script type="text/javascript"> 
     //查询部门所有的的名称这里用到的是Jquery的ajax请求
   function selectAllDnames(){
   $.ajax({
                  //请求方式  
type:"GET",
                  //请求地址
url:"jsontest!queryDepartAlldname.action", 
success:function(msg){
     var data=eval(msg ); //将后台接收的数据转型为数组
                 //获取我的select的对象
     var select = document.getElementById("dname");
     select.length=0; //要清空select
     select.options.add(new Option("---请选择----","---请选择----"));            //循环并动态的添加option
     for(var i=0;i<data.length;i++){
     select.options.add(new Option(data[i].dname,data[i].did));
    
     }
  
   }


});
  
   }   

</script>


页面中的出现<select的地方:
所属部门:
    <select Class="inputCss" id="dname" name="dname">
     <option selected="selected">---请选择---</option> 
  
    </select>