举个例子 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>My JSP 'ajax.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<%=basePath%>res/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").bind("click",function(){
$.ajax({
type:"post",
url:"<%=basePath%>ajax.action",
data:"array="+$("#text").val(),
datatype:"json",
success:function(msg){
alert(msg);
},
error:function()
{
alert("失败");
}
});
})
});
</script>
</head> <body>
<input id = "text" type = "text" >
<input id = "button" type = "button" value ="提交">
</body>
</html>
后台:
package test; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.Action; public class ajax {
private String str;
public String ajax()
{
HttpServletRequest request = ServletActionContext.getRequest(); str = "action处理请求后返回给ajax参数:"+request.getParameter("array");
System.out.println(request.getParameter("array")); return Action.SUCCESS;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
} }
Struts2 配置文件:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"/>
<package name="example" extends="json-default">
<action name = "ajax" class = "test.ajax" method = "ajax">
<result type = "json">
<param name = "root">str</param>
</result>
</action>
<action name="*">
<result>/WEB-INF/content/{1}.jsp</result>
</action>
</package>
</struts>
所用到的jar包:
所用到的jQuery文件,自行下载。
转载请注明出处。