strut2使用ajax
一、导入包:
json-lib-2.3-jdk15.jar
ezmorph-1.0.6.jar
struts2-json-plugin-2.2.3.jar(这个如果你是用myeclipse 集成的ssh框架。那么这个包默认就有了)
二、js文件
json.js
prototype.js
三、struts.xml
<package name="TestAjax" extends="json-default" namespace="/">
<action name="bloga" class="BlogAjaxAction">
<result type="json" />
</action>
</package>
- 注意点一:<package name="TestAjax" extends="json-default" namespace="/"> 的extends属性值为json-default,不再是以前的struts-default
- 注意点二:<result type="json" /> 这个result type改为。并且这样写就可以了。
- 注意点三:<action name="bloga" class="BlogAjaxAction"> 这个里边的class属性就是你在applicationContext.xml中配置的那个id="BlogAjaxAction"的bean。这里做了个引用。
四、applicationContext.xml没什么特别的,就和其他的Action一样配置就ok。
五、Action类的写法
public class BlogAjaxAction extends ActionSupport { /** * */ private static final long serialVersionUID = 3213032717047085979L; private BlogBiz blogbiz; @JSON(serialize=false) public BlogBiz getBlogbiz() { return blogbiz; } public void setBlogbiz(BlogBiz blogbiz) { this.blogbiz = blogbiz; } private String result; public String getResult() { return result; } public void setResult(String result) { this.result = result; } private Page<BlogInfo> pages; @JSON(serialize=false) public Page<BlogInfo> getPages() { return pages; } public void setPages(Page<BlogInfo> pages) { this.pages = pages; } @JSON(serialize=false) public int getIndex() { return index; } @JSON(serialize=false) public int getSize() { return size; } public void setIndex(int index) { this.index = index; } public void setSize(int size) { this.size = size; } private int index; private int size; public String execute() throws Exception { pages=blogbiz.list(index, size); result =JSONObject.fromObject(pages).toString(); //result = "ajax测试"; return SUCCESS; }
注意点:1、@JSON(serialize=false)表示这个属性不返回到client,注意用到getXX方法上。
2、下面这段代码中的result就是要返回给client的属性,所以及没加@JSON(serialize=false)这个东西,当然也可以加,就是把serialize改为true。如果不加,就是默认要返回client的。
private String result; public String getResult() { return result; } public void setResult(String result) { this.result = result; }
3、execute方法中通过这样就把一个对象转为json字符串JSONObject.fromObject(pages).toString();然后赋值给result。
六、jsp的写法。
<script src="static/js/ajaxsurpport/json.js" type="text/javascript"></script> <script src="static/js/ajaxsurpport/prototype.js" type="text/javascript"></script> <input type="button" name="test" value="ceshi" onclick="test()" /> <script type="text/javascript"><!-- function test(){ alert('start'); new Ajax.Request("bloga.action",{method: 'post',onComplete: getTest}); function getTest(originalRequest){ document.getElementById("test").innerHTML=originalRequest.responseText.evalJSON(true).result.evalJSON(true).rs[0].title; } alert("end"); } --></script> <div id="test"></div>
注意点:1、引用js文件。
2、new Ajax.Request("bloga.action",{method: 'post',onComplete: getTest});这样请求ajax
3、返回的json数据这样转换:originalRequest.responseText.evalJSON(true).result.evalJSON(true).rs[0].title;
OK! 结束了。
posted on 2013-07-19 10:43 ct_charles 阅读(191) 评论(0) 编辑 收藏 举报