struts2跟jquery,json的结合小结
struts2跟jquery,json结合的一个小例子,小结下:
1页面
<formaction=""id="introForm"><labelfor="name">EnterYourName</label>
<inputname="name">
<inputtype="submit">
</form>
2在ACTION部分
publicclassAjaxActionsextendsActionSupport{
privateStringname;
privateStringgreeting;
privateList<string>countryList;
privateMap<string,long>countryMap;
publicStringsayHi(){
greeting="HI"+name;
countryList=newArrayList();
countryList.add("US");
countryList.add("UK");
countryList.add("Russia");
countryMap=newHashMap();
countryMap.put("US",1L);
countryMap.put("UK",2L);
countryMap.put("Russia",3L);
returnActionSupport.SUCCESS;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetGreeting(){
returngreeting;
}
publicvoidsetGreeting(Stringgreeting){
this.greeting=greeting;
}
publicList<string>getCountryList(){
returncountryList;
}
publicvoidsetCountryList(List<string>countryList){
this.countryList=countryList;
}
publicMap<string,long="">getCountryMap(){
returncountryMap;
}
}
3配置
<struts>
<packageextends="struts-default,json-default"name="ajax-package"namespace="/ajax">
<actionclass="sample.AjaxActions"method="sayHi"name="sayHi">
<resulttype="json">
</result></action>
</package>
</struts>
4最后在前端把表单的信息送出,并且把后端的信息简单取出
这里只是通过FIREFOX的CONSOLE输出
,注意这里还演示了如何输出JSON格式的MAP和LIST
$(function(){
$("#introForm").submit(function(){
varformInput=$(this).serialize();
$.getJSON('ajax/sayHi.action',formInput,function(data){
$('.result').html(''+data.greeting+'
');
$.each(data.countryList,function(index,value){
console.log("value"+value);
});
$.each(data.countryMap,function(key,value){
console.log("key"+key+",value"+value);
});
});
returnfalse;
});