功能:利用struts2+ajax从后台获取数据,并且数据以json格式传递
必备组建:struts2,juqery,struts2 json 插件
步骤:
1.ation应该继承 ActionSupport
package com.thtf.lotterymanager.index.action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.thtf.common.BaseAction;
@Scope("prototype")
@Controller("indexAction")
public class IndexActjion extends ActionSupport {
private static Logger logger = Logger.getLogger(IndexActjion.class);
private String json;
public String verifyAuthcode(){
try {
String rand = (String) BaseAction.getSession("rand");
JSONObject jo = new JSONObject();
if (rand != null && rand != "" && rand.equals(authcode)) {
json = jo.element("result", "1").toString();
} else {
json = jo.element("result", "0").toString();
}
logger.info(json);
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
}
2.配置Struts.xml文件
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
json
注意:配置文件中标红的json必须跟必须跟你action中的字段名称保持一致,并且要在action中声明get,set方法
3.前台jsp页面使用jquery方式与后台交互
//登陆验证
$(function(){
$("#loginForm").submit(function(){
var userName = $("#username").val();
var pwd = $("#pwd").val();
var authcode = $("#authcode").val();
if(authcode==""){
alert("验证码不为空!");
return false;
}else{
$("#authcodeMsg").text("");
var res;
$.ajax({
url:"index_verifyAuthcode.action",
type:"POST",
data:({authcode:authcode}),
async:false,
dataType:"json",
success:function(data){
var m = eval("("+data+")");
if(m.result=="0"){
$("#authcodeMsg").text("验证码错误!");
res = m.result;
}
}
});
if(res=="0"){
return false;
}
}
});
});