在此输入代码 使用struts2也有些时间了,对于其中ajax应用不是很了解,正巧在项目中碰到需要用ajax实现的功能,仔细研究了一番,终于搞定,现分享给大家。
1.导入相应的jar包,struts2-json-plugin-2.3.7.jar是必须的
2.编写Action
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
import com.opensymphony.xwork2.ActionSupport;
/**
* json 示例类
* user: joe
* Date: 13-5-20
* Time: 下午8:24
*/
public class DemoAction extends ActionSupport {
private String tel;
private String msg;
public String getJsonStr() {
if (tel.equals("18801136189")){
setMsg("correct");
}
return SUCCESS;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
3.xml文件配置
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="json" extends="json-default">
<action name="json_*" class="demo.DemoAction" method="{1}">
<result type="json"></result>
</action>
</package>
</struts>
4.js代码编写
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>index</title>
<script type="text/javascript" src="../scripts/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.post("json_getJsonStr.action",{tel:"18801136189"},function(json){
alert(json.msg)
},"json");
});
});
</script>
</head>
<body>
<input type="button" id="btn"/>
</body>
</html>
后记:掌握知识还得多写些demo才管用.