Structs2 Json Ajax实现
1.建立my.struts2.web.JSONResult(自定义结果类,只要实现com.opensymphony.xwork2.Result接口)
package my.struts2.web;
import java.io.PrintWriter;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;
import net.sf.json.JSONArray;
public class JSONResult implements Result{
@Override
public void execute(ActionInvocation invocation) {
try {
ServletActionContext.getResponse().setContentType("text/plain");
PrintWriter responseStream = ServletActionContext.getResponse().getWriter();
ValueStack valueStack = invocation.getStack();
Object jsonModel = valueStack.findValue("jsonModel");
responseStream.println(JSONArray.fromObject(jsonModel));
} catch (Exception e) {
System.out.println(e);
}
}
}
2.structs2 XML配置
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml"/>
<package name="tutorial" extends="struts-default" >
<result-types>
<result-type name="jsonResult" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Structs2 AjaxTest</title>
<script type="text/javascript">
function ajaxResponse(){
if(req.readyState==4){
var myObject = eval('(' + req.responseText + ')');
alert("name:"+myObject[0].name);
alert("ps:"+myObject[0].ps);
}
}
function ajaxPost(callback, url) {
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send(null);
}else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send();
}
}
}
</script>
</head>
<body onload="ajaxPost(ajaxResponse,'/s2/ajaxTest.action')">
</body>
</html>
1 楼 cloudbee 2011-09-17 Nice code. Test passed.