Struts2 使用ajax

1. 项目中添加支持json的相关jar包, 本例中使用的是 fastjson-1.1.36.jar, struts2-json-plugin-2.3.30.jar

2. struts2 配置文件中,对页面跳转的路径进行添加和配置, 继承的的不再是struts-default, 而是 json-default

	<!-- 继承的的不再是struts-default, 而是 json-default -->
	<package name="ajax" namespace="/ajax" extends="json-default">
		<!-- 博客内容保存成功后,跳转到列表页面 -->
		<action name="saveblog" class="org.navis.action.BlogAction" method="saveblog">
			<!-- 配置返回类型 ,json, 取消name 属性,也不再设置跳转路径 -->
			<result type="json">
				<!-- 添加参数,功能为:不序列化Action里为null的字段 -->
				<param name="excludeNullProperties">true</param> 
			</result>
		</action>
	</package>

3. 后台Action 方法中,返回值必须为String 类型

/**
* @description  接收前台富文本编辑器中的内容
*/
public String saveblog(){
System.out.println("title:" + getTitle());
System.out.println("sticker:" + getSticker());
System.out.println("textcontent:" + getTextcontent());
//String com.opensymphony.xwork2.Action.SUCCESS = "success"
return SUCCESS;
}

4. 前台Ajax 脚本为:

    <!-- Bootstrap core JavaScript -->
    <script src="${basepath}/static/js/jquery-1.12.3.js"></script>
    <script src="${basepath}/static/js/jquery.base64.js"></script>
    <script src="${basepath}/static/js/bootstrap.js"></script>
	<script src="${basepath}/static/js/editor.js"></script>
	<script>
		$(document).ready(function() {
			$.base64.utf8encode = true;
			$("#textEditor").Editor();
			
			$("#submit").click(function(){
				var title = $("#title").val();
				var sticker = $("#sticker").val();
				var code = $(".Editor-editor").html();
				if(title == null || ""==title || sticker==null || ""==sticker || code==null || ""==code){
					$('#notice').modal({
						show:true
					})
					return;
				}
				$("#textcontent").val(code);
				var data = $("#blogform").serialize();
				$.post("${basepath}/ajax/saveblog.html",data,function(){
					window.location.href="${basepath}/blog/list.html";
				},"json");
			});
		});
	</script>

猜你喜欢

转载自617211950.iteye.com/blog/2321475