日期:2014-05-16  浏览次数:20541 次

struts2跟jquery,json的结合小结
struts2 跟jquery,json结合的一个小例子,小结下:

1 页面
  <form action="" id="introForm"><label for="name">Enter Your Name</label>
            <input name="name">
            <input type="submit">
        </form>

2 在ACTION部分
  public class AjaxActions extends ActionSupport{

    private String name;
    private String greeting;
    private List<string> countryList;
    private Map<string,long> countryMap;

    public String sayHi(){
       
        greeting="HI " +name;

        countryList=new ArrayList();
        countryList.add("US");
        countryList.add("UK");
        countryList.add("Russia");

        countryMap= new HashMap();
        countryMap.put("US",1L);
        countryMap.put("UK",2L);
        countryMap.put("Russia",3L);

        return ActionSupport.SUCCESS;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGreeting() {
        return greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }

    public List<string> getCountryList() {
        return countryList;
    }

    public void setCountryList(List<string> countryList) {
        this.countryList = countryList;
    }

    public Map<string, long=""> getCountryMap() {
        return countryMap;
    }

}
3 配置
  <struts>
    <package extends="struts-default,json-default" name="ajax-package" namespace="/ajax">
       
            <action class="sample.AjaxActions" method="sayHi" name="sayHi">
                <result type="json">
            </result></action>

    </package>
</struts>

4 最后在前端把表单的信息送出,并且把后端的信息简单取出
这里只是通过FIREFOX的CONSOLE输出
,注意这里还演示了如何输出JSON格式的MAP和LIST
$(function(){

$("#introForm").submit(function(){
 
  var formInput=$(this).serialize();
 
  $.getJSON('ajax/sayHi.action', formInput,function(data) {
  
   $('.result').html('' + data.greeting + '
');

   $.each(data.countryList,function(index, value){
    console.log("value " + value);
&nbs