最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
springmvc和js前端的数据传递和接收方式(两种)
时间:2022-06-29 00:40:41 编辑:袖梨 来源:一聚教程网
在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 staticString 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 MapqueryProvince(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+""); } } });