您的位置:首页 > Web前端 > JQuery

struts2+jquery+ajax的使用

2015-07-02 08:49 543 查看
记录一下自己的使用经验。

//查看我的预约页面,通过ajax请求实现局部刷新请求分布数据功能
function getPageByAjax(currentPage,keyword){
var pageSize = $("#pageSizeSelect").val();
var ajaxparams = {  "som.currentPage":currentPage,
"som.keyword":keyword,"newPageSize":pageSize
};
$.ajax({
url :"showMyAppoints!getTbodyByAjax.action",
type : "post",
data:ajaxparams,
dataType : "html",
async : true,
success : function(data){
$("#ajaxRefreshTbody").empty();
$("#ajaxRefreshTbody").html(data);
},
error : function(){
alert("网络错误!");
}
});
}
在用ajax往后台传参数的时候,可以传一个变量,如newPageSize,也可以传一个变量的属性值,如som.keyword.

private ShowOrderModel som;//页面传回来的pageModel

private String newPageSize;//页面重新设置的每页显示记录数

dataType可以是html或者json,如果是html的话,可以请求返回一个子页面,然后异步刷新网页的一部分

这是ajax请求后台的action方法

public String getTbodyByAjax(){
//doSomething...
return "AJAX_GET_Tbody";
}
这个配置文件配置返回一个页面

<action name="showMyAppoints" class="showMyAppointsAction">

<result name="AJAX_GET_Tbody">wbyy/appointsAjaxTbody.jsp</result>

</action>

如果用ajax不是想返回一个页面的话,那也可以返回json数据。用法如下

//判断验证码是否正确  如果正确则提交预约ID到后台取消预约
$("#sureCancel").click(function(){
if($("#validateCode").val().length==6){
var ajaxparams = {ajaxValidateCode:$("#validateCode").val()};
$.ajax({
url :"appointCancle!testValidateCode.action",
type : "post",
data:ajaxparams,
dataType : "json",
async : true,
success : function(data){
if(data["status"]=="1"){
alert("预约取消成功!");
window.location.href="appointCancle!appointCancle.action?appointId="+$("#appointIdHidden").val();
}else{
allowGetValidate();
flagToStop = true;
alert(data["message"]);
}
},
error : function(){
alert("网络错误!");
}
});
}else{
alert("请输入6位验证码!");
}
});
public String testValidateCode() throws IOException{
ValidateCodeUtil.testValidateCode(ComConstant.CANCEL_VALIDATE_MAP, ajaxValidateCode);
return NONE;
}

public static void testValidateCode(String type,String ajaxValidateCode) throws IOException{
HashMap<String,String> resultMap = new HashMap<String,String>();
HttpSession session = ServletActionContext.getRequest().getSession();
HttpServletResponse response = MyHttpUtil.getResponse();
if(session.getAttribute(type)!=null){
@SuppressWarnings("unchecked")
HashMap<String,String> codeMap = (HashMap<String, String>) session.getAttribute(type);
String validateCode = codeMap.get("validateCode");
String createTime = codeMap.get("createTime");
if(validateCode.equals(ajaxValidateCode) && DataFormatUtil.timeInMinute(15, Long.parseLong(createTime), new Date().getTime())){
resultMap.put("status", "1");
resultMap.put("message", "验证码正确!");
session.removeAttribute(type);
}else{
resultMap.put("status", "0");
resultMap.put("message", "验证码错误!请重新点击获取验证码!");
session.removeAttribute(type);
}
}else{
resultMap.put("status", "0");
resultMap.put("message", "验证码已失效,请重新点击获取验证码!");
}
response.getWriter().print(JsonUtil.toString(resultMap));
}
}


action返回值什么都可以吧 在struts配置文件里不用配置result就行了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: