struts+ajax+json 完整例子

核心jar包准备:xwork-2.1.2.jar struts2-core-2.1.6.jar jsonplugin-0.34.jar json.jar

用例介绍:
页面上有一个两个div和一个按钮,当点击按钮时,去后台请求数据,并将请求的内容刷新到div1和div2

页面:

<input name="a" type="button"  value="ss" onclick="test()"/>
	 
	 <div id="div1">
	 </div>
	 <div id="div2">
	 </div>

 

js如下:

function test() { 
var xmlObj = null; 

if (window.XMLHttpRequest) { 
xmlObj = new XMLHttpRequest(); 
} else if (window.ActiveXObject) { 
xmlObj = new ActiveXObject("Microsoft.xmlHTTP"); 
} else { 
return; 
} 

//回调: 
xmlObj.onreadystatechange = function() { 
if (xmlObj.readyState == 4) { 
if (xmlObj.status == 200) { 

var oJSON = eval('(' + xmlObj.responseText + ')'); 
  //或者 var oJSON = JSON.parse(oRequest.responseText); (效果一样) 
alert(oJSON.result); 
//将result的返回值放到div1里面 
var div1 = document.getElementById("div1"); 
div1.innerHTML = oJSON.result; 
//将aa的返回值放到div2里面 
var div2 = document.getElementById("div2"); 
div2.innerHTML = oJSON.aa; 

} else { 
alert(" status : " + xmlObj.status); 
} 
} 
} 
var url = "<%=path%>/CustomerManage_jsonTest.action"; 
xmlObj.open('POST', url, true); 
xmlObj.setRequestHeader("Content-Type", "application/json"); 
xmlObj.send(null); 

} 

 
action:

public String jsonTest() throws IOException{ 

this.setResult("rrrrrrrrrrr222222222222"); 
this.setAa("aaaaaaaaaaaaaaaaaa"); 
System.out.println("sssssssssssss"); 
return "left11"; 
} 

String result = null; 

String aa = null; 

public String getAa() { 
return aa; 
} 

public void setAa(String aa) { 
this.aa = aa; 
} 

public String getResult() { 
return result; 
} 


public void setResult(String result) { 
this.result = result; 
} 

 
struts.xml:

<package name="crm" extends="json-default"> 

<action name="CustomerManage_*" class="com.xuehuile.crm.action.CustomerManageAction" 
method="{1}"> 
<result type="json" name="left11"> 
<!-- 把aa和result两个参数以json的格式带到页面!> 
<param name="includeProperties">aa,result</param> 
</result> 


</action> 
</package> 

 

所有的代码已经全部在上面了,相信按照这个例子可以实现将action中的数据带到页面

 

你可能感兴趣的:(json,xml,Ajax,struts,Microsoft)