在struts2 的ajax里,实现比较简单。
从页面开始吧
1.写好页面,页面里写好实现ajax 的函数,我使用jQuery 的$.ajax({……….}) 的方式实现,待会儿会贴出代码
2.创建好处理ajax请求 的Action 类
3.在struts2 的struts.xml 核心配置文件中配置访问此Action 的Action元素
4.如果一切正常就不需要调试了
脚本↓↓↓
function submit(){
var content=$("#content");
if(content.val().length>0&&content.val().length<=200){ // jquery 里面的值是val()
alert(content.val());
var infoId=$("#infoId").val(); alert(infoId);
var data={content:content.val(),infoId:infoId};
$.ajax({
url:"replyInformation",
data:data,
type:"post",
dataType:"json",
success:function(result){
$("#norm").after("发表于:"+result.replyTime+"<br/>"+result.content+"<br/><br/>");
}
})
}else{
alert("请填写回复内容");
}
return ;
}
页面元素↓↓↓
<input type="hidden" id="infoId" value="<s:property value="infoId"/>" />
<h1><s:property value="info.title"/></h1>
发表于:<s:property value="info.reportTime"/> <br/><br/>
<s:property value="info.content"/> <br/><br/>
<h3 id="norm">读者回应<br/><br/></h3>
<s:iterator value="replyList" id="reply">
发表于:<s:property value="replyTime"/> <br/>
<s:property value="content"/> <br/><br/>
</s:iterator>
快速回复(字数200以内): <br/>
<textarea id="content" rows="" cols=""></textarea> <br/>
<input type="button" value="提交" onclick="submit()" /><a href="index.jsp">返回首页</a>
处理请求的Action↓↓↓
private String content;
private Integer infoId;
public String replyInformation(){
reply=replyService.save(content,infoId);//保存回复内容
Information information=informationService.updateReplyCountAndLastPostTime(infoId);//修改资讯last time and count
return "success";
}
配置struts2 的核心文件↓↓↓
<action name="replyInformation" class="cn.jbit.test.action.InformationAction" method="replyInformation">
<result type="json" >
<param name="root">reply</param>
</result>
</action>
然后最后就是jar 包的问题了
需要struts2-json-plugin-2.2.1.jar
jQuery类库:jquery-1.8.3.min.js
如有遗漏欢迎指出^_^