java 实现自动编译成json struts2 中不用配置json等jar包来实现低耦合,低入侵式ajax访问返回数据

1.首先要准备一个JSONUtile工具类,来实现数据的JSON转换javascript

具体代码能够从这里下载:html

 java普通类编译成json但只是当前类的有getter、setter方法的版本:java

http://download.csdn.net/detail/songylwq/5896369ajax

 

java本身修改的支持public属性、父类属性的json自动编译的工具类版本:json

http://download.csdn.net/detail/songylwq/5896385框架

 

2.struts2框架搭建好后,在BaseAction中构建变量、方法dom

protected String ajaxData;

	public String getAjaxData() {
		return ajaxData;
	}
	public void setAjaxData(String ajaxData) {
		this.ajaxData = ajaxData;
	}


3.在struts.xml配置文件中配置全局返回页面
jsp

<global-results>
    <result name="ajax" >/ajax.jsp</result>
</global-results>

ajax.jsp页面代码:

<%@ page language="java" pageEncoding="UTF-8"
	import="org.main.common.util.*"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:property value="ajaxData" escape="false"/>

设置escape="false";若是不设置此属性,返回的标点符号会变成转义字符,如:“双引号”会变成“&quot;”

public String test_json() throws Exception{
	//逻辑代码
 ajaxData = 返回数据;
	return SUCCESS;
}

4.页面中js代码:工具

<script type="text/javascript">
	function testJSON(){
		$.ajax({url:'test_json.action',
			data:{time:Math.random()},
			dataType: "json",
		   success:function(res){
				   alert(res);
				   $.each(res,function(i,n){
					   alert(i+":"+n["orderNo"]);
					})
			}
		});
	}
</script>
相关文章
相关标签/搜索