您的位置:首页 > 编程语言 > Java开发

Struts2+ajax+json整合简介

2014-02-06 15:33 323 查看
一、准备好jar包,不要小看这一步,万事开头难。。总结起来有以下三种搭配。

1.   xwork-core-2.1.6.jar和struts2-json-plugin-2.1.8.jar。如果你想使用struts2-json-plugin-2.1.8.jar这种支持方式,你的xwork-core-*.jar不能选择2.2.1及以上版本,因为xwork-core-*.jar的2.2.1及以上版本中没有了org.apache.commons.lang等包。启动tomcat的时候会出现:java.lang.NoClassDefFoundError:
org.apache.commons.lang.xwork.StringUtils。

 

2.   xwork-2.1.2.jar和jsonplugin-0.34.jar。如果想用jsonplugin-0.34.jar这种支持方式,那需要切换你的xwork-core-*.jar为xwork-2.1.2.jar。因为jsonplugin-0.34.jar需要com.opensymphony.xwork2.util.TextUtils

这个类的支持。而xwork-core-*.jar的2.2.1以上版本均为找到该类,且在xwork-core-2.1.6.jar中也没有该类。

3 .struts2.3.7的版本,适合struts2-json-plugin-2.3.4.1.jar与json-lib-2.3-jdk15.jar

二、下面看下action是啥吧。

public String editProblem(){
question=(Question) this.getSession().get("QUESTION_INFO");
this.pid=String.valueOf(question.getId());
question.setContent(this.newContent);
question.setModifyDateTime(this.getCurrentDate());
showProblemsLogic.updateProblem(question);//更新数据库记录
return SUCCESS;
}

很简单,是个编辑问题的方法,笔者正在做一个互动问答平台,用户在提问之后,还可以编辑自己的问题。
上面就是实现这个功能的action代码。可以注意到,这个action里面有很多属性,struts.xml可以这样写。

<action name="editProblem" class="problemsAction" method="editProblem">
<result name="input">/problems.jsp</result>
<result type="json">
<param name="includeProperties">newContent</param>
</result>
</action>

includeProperties这个参数的配置对应的是下面这段ajax提交代码中的success回调函数中的data,如果data需要更多的内容,则可以在includeProperties参数里面添加更多的属性。  这个参数的配置很关键,配置错了,success回调函数就不会执行了,所以一定要注意!

三、再来看下ajax函数是怎么写的吧

<script>
$(document).ready(function(){
$("#edit_content_button").click(function() {
var params = $("#edit_form").serialize();//讲指定表单中的参数转换为查询字符串
//使用jQuery中的$.ajax({});Ajax方法
$.ajax({
url:"editProblem",//这个是对应的action名称
type:"POST",
data:params,
dataType:"json",
success:function(data){	ajax请求提交成功后的回调函数
$("#qcontent").css("display","none");
$("#newqContent").empty();
$("#newqContent").append(data.newContent);
$('#edit_form').toggle();
alert("修改成功!");
},
error:function(data){
alert(arguments[1]);
}
});
});
});
</script>

这样,整合就算初具规模了,可以实现在struts2下,页面无刷新的表单提交了~




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: