Spring MVC ,jqueryAJAX,Json三步整合实例 (转自趣友网)

来源:互联网 发布:淘宝网怎样申请退货 编辑:程序博客网 时间:2024/04/29 22:34
 
快速预览:  

1.首先在你的 springMVC servlet配置文件上面加上这个配置,让spring自动把你的对象转换成JSON对象 

 

<!-- ajax配置    需要第三方jar:jackson-core-lgpl-1.6.9,jackson-mapper-lgpl-1.6.9-->
 
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > 
    <property name="messageConverters"> 
        <list > 
            <ref bean="mappingJacksonHttpMessageConverter"/> 
        </list> 
    </property> 
</bean> 
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
    <property name="supportedMediaTypes"> 
        <list> 
            <value>text/html;charset=UTF-8</value> 
        </list> 
    </property> 
</bean>

别忘了 lib里面添加jar包 jackson-core-lgpl-1.6.9,jackson-mapper-lgpl-1.6.9 也可以用最新的版本

 


 

2.springMVC实现AJAX非常容易 只需要一个注解@ResponseBody就搞定了

返回对象可以是 普通对象  或者 map list 等集合对象 都会自动帮您转换成json对象

 

@ResponseBody
 @RequestMapping("/c")
 public  HuiyiTxt channelAjax(HttpServletRequest request,HttpServletResponse response ) {
  Integer id = Integer.parseInt(request.getParameter("channelId"));
  Integer huiyiId = Integer.parseInt(request.getParameter("huiyiID"));
 
  
  HuiyiTxt huiyiTxt = null;
  List<HuiyiTxt> list = huiyiTxtDao.findHuiyiTxtByHuiyiChannel(new HuiyiChannel(id),new Huiyi(huiyiId));
  if (null != list && list.size() >0) {
   huiyiTxt = list.get(0);
  }

  
  return huiyiTxt;
  
 }

 

3,。最后一步就是获得返回的json对象 ,用jquery做也是比较简单的 只需要使用jquery内置的 $.getJSON方法即可轻松获得返回的json对象

 

 

   <script type="text/javascript">
    $(document).ready(function() {
     
     $(".menu li").click(function() {
      $.getJSON("/huiyi/c"+"?"+Math.random()
      {channelId:$(this).val(),
      huiyiID:"${huiyi.id}" },
      function(data) {  //这里返回的就是已经包装好的json对象,剩下的根据需要取出想要的数据
       alert(data.txt);
      });
     });
    });

    </script> 

顺便提一下, Ajax 默认的缓存清理方法 url "+"?"+Math.random()这样就可以保证你每次调用ajax得到的都是从 数据库返回最新数据 而不是缓存里的。

 

转自 趣友网 http://www.funfriends.com.cn/a/379

原创粉丝点击