Struts2 + Json +jQuery 整合
Struts2+Json+jQuery整合
2011-12-01 16:55:55| 分类: AJAX | 标签:struts2+json+jquery struts2与jquery整合 |字号 订阅
PS:本文将介绍三者如何通讯的问题,其中Struts2中json插件的配置请见:http://blog.163.com/asd_wll/blog/static/2103104020111115817375/
一、Struts2的配置
(1)JsonAction.action
public class JsonAction extends ActionSupport { private List<User> mList=new ArrayList<User>();
public List<User> getmList() { return mList; } public String execute() throws Exception { mList.add(new User("wll","男","xc_wll@yahoo.com.cn")); mList.add(new User("caocao","男","caocao@yahoo.com.cn")); mList.add(new User("daqiao","女","daqiao@yahoo.com.cn"));
return SUCCESS; } } |
(2)User.java
public class User { private String name; private String sex; private String email; } |
(3)struts.xml
<struts> <package name="struts2.json" extends="json-default"> <action name="jsonAction" class="struts2.json.JsonAction"> <result type="json"> //默认情况是把action中的所有property都输出到json数据中 </result> </action> </package> </struts> |
二、JSP(jQuery页面)
<html> <head> <title>jQuery.ajax.json.struts2</title> <meta http-equiv="content-type" content="text/html; charset=GBK"> <style type="text/css"> body< xmlnamespace prefix ="st1" ns ="isiresearchsoft-com/cwyw" />{font-size:13px} .divFrame{width:250px;border:solid 1px #666} .divFrame .divTitle{padding:5px;background-color:#eee} .divFrame .divContent{padding:8px} .divFrame .divContent .clsShow{font-size:14px} .btn{border:#666 1px solid;padding:2px;width:60px; filter:progid:DXImageTransform.Microsoft .Gradient(GradientType=0,StartColorStr=#ffffff, EndColorStr=#ECE9D8);} form{padding:0px;margin:0px} } </style> <script type="text/javascript" src="js/jquery-1.6.3.js"></script> <script type="text/javascript"> $(function() { $.ajaxSetup({ type:"GET",url:"jsonAction.action",dataType:"json" })
$("#Button1").click(function(){ $.ajax( { success:function(data) { ShowData(data,"姓名","name"); } }) })
$("#Button2").click(function(){ $.ajax( { success:function(data) { ShowData(data,"性别","sex"); } }) })
$("#Button3").click(function(){ $.ajax( { success:function(data) { ShowData(data,"邮箱","email"); } }) })
function ShowData(d,n,v) { //json数据的输出:$.each(property,value). $("#divTip").empty(); var strHTML=""; $(d.mList).each(function(InfoIndex,Info) { var $strUser=$(this); strHTML+=n+":"+Info[v]+"<hr/>"; }) $("#divTip").html(strHTML); } })
</script> </head>
<body> <div class="divFrame"> <div class="divTitle"> <input id="Button1" type="button" class="btn" value="姓名"/> <input id="Button2" type="button" class="btn" value="性别"/> <input id="Button3" type="button" class="btn" value="邮箱"/> </div> <div class="divContent"> <div id="divTip" class="clsShow"></div> </div> </div> </body> </html> |