java类代码:
package com.rain.json.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
@ParentPackage("json-default")
@Results({ @Result(name = "jsonExample", type = "json") })
public class JsonExampleAction {
private String result;
private String type;
@Action(value = "/json/jsonExample")
public String jsonExample() {
if ("json".equals(type)) {
result = "json";
} else {
result = "other";
}
return "jsonExample";
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
jsp页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>jsonExample</title>
<script type="text/javascript" src="<%=basePath%>js/base/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function jsonExample(){
$.ajax({
type : "POST",
dataType : "json",
data : {type:"json"},
url : "<%=basePath%>json/jsonExample.do",
async : false,
success : function(data) {
if (data.result == "json") {
alert("json");
} else if (data.result == "other") {
alert("other");
}
}
});
}
</script>
</head>
<body>
<input type="button" value="json" οnclick="jsonExample();"/>
</body>
</html>