您的位置:首页 > 编程语言 > Java开发

struts2 json

2013-11-03 16:55 281 查看
1.      拷贝struts-2.3.4-all\lib下的

commons-beanutils-1.8.0.jar

commons-collections-3.1.jar

commons-lang3-3.1.jar

comm
4000
ons-logging-1.1.1.jar

ezmorph-1.0.6.jar

json-lib-2.3-jdk15.jar

struts2-json-plugin-2.3.4.jar

到工程web-inf/lib下

2.      Action:

 

publicclass DeptAction {
    private IDeptService
deptservice;
    private String
result;//用来存放json
    public String findAllDept(){
       List<Department> depts =
new
ArrayList<Department>();
       deptservice =
new DeptServiceImpl();
       depts =
deptservice.findAllDept();
       JSONArray ja = new JSONArray();
       for(Department d:depts){
           JSONObject jobj=
new
JSONObject();
           jobj.accumulate("deptno",d.getDeptno());
           jobj.accumulate("deptname",d.getDeptname());
           ja.add(jobj);
       }
       ///JSONArray.fromObject(depts).toString();第二种方式转json
       result = 
ja.toString();
       return"success";
    }
    public IDeptService getDeptservice() {
       returndeptservice;
    }
    publicvoid setDeptservice(IDeptService deptservice) {
       this.deptservice = deptservice;
    }
    public String getResult() {
       returnresult;
    }
    publicvoid setResult(String result) {
       this.result = result;
    }
}

3.  STRUTS.XML

 

<package
name="default"
namespace="/"extends="json-default">
    <action
name="deptinfo"
class="com.etc.web.DeptAction"method="findAllDept">
       
<result type="json"></result>
    </action>
</package>

4.

$(document).ready(function(){
        $.ajax({
        url:"<%=basePath%>deptinfo",
        type:"POST",
        dataType:"json",
        success:function(data){
          
var
dept = eval("("+data.result+")");//将字符串转换到json对象
           var
html="";
           $.each(dept,function(i,p){
               html+="<optionvalue='"+p.deptno+"'
>"+p.deptname+"</option>"
           });
           $("#deptinfo").html(html);
        }
        });
    });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: