一聚教程网:一个值得你收藏的教程网站

最新下载

springmvc和js前端的数据传递和接收方式(两种)

时间:2017-12-31 16:15:00 编辑:猪哥 来源:转载

在springmvc中controller的结果集可通过json格式传到js前端接受,也可以通过Map传给前端,具体实现如下

1,通过json格式传递

controller层实现如下

 @RequestMapping("queryCityInfo") 
  @ResponseBody 
  public String queryCityInfo()throws Exception{ 
     String provinceId = getString("id"); 
     @SuppressWarnings("rawtypes") 
    List cityList = personalService.queryCity(provinceId); 
     if(null != cityList && cityList.size() >0 ){ 
      String json = JSONUtils.toJSONString(cityList);      
      super.outStr(json); 
     } 
    return null; 
  } 

protected void outStr(String str) 
  { 
    try 
    { 
      response.setCharacterEncoding("UTF-8"); 
      response.getWriter().write(str); 
    } 
    catch (Exception e) 
    { 
    } 
  } 
public static  String toJSONString(List list) 
  { 
    JSONArray jsonArray = JSONArray.fromObject(list); 
     
    return jsonArray.toString(); 
  } 

js端接受如下

function selectBankCity(id){ 
  $.ajax({ 
    url:baseAddress+"queryCityInfo.do?provinceId="+id, 
    type:'get', 
    dataType:'json', 
    success:function(data){ 
      $('#custBankArea').empty(); 
      $('#custBankArea').append(""); 
      for(var i=0;i"+data[i].cityName+""); 
      } 
    } 
  }); 
} 

2,通过Map传递

controller层实现如下

@RequestMapping("queryProvince") 
  @ResponseBody 
  public Map queryProvince(HttpServletRequest request,HttpServletResponse response){ 
    Map map = new HashMap(); 
    try { 
      @SuppressWarnings("rawtypes") 
      List provinceList = personalService.queryProvince(); 
      if(null != provinceList && provinceList.size() >0 ){ 
        map.put("province", provinceList); 
      }  
    } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
    return map; 
  } 

js端接受如下

$.ajax({ 
      url:baseAddress+"queryProvince.do", 
      type:"get", 
      success:function(resData){ 
        var data = resData.province; 
        for(var i=0;i"+data[i].provinceName+""); 
        } 
      } 
    }); 

网站留言

热门栏目