springmvc接收js数据 springmvc和js前端的数据传递和接收方式(两种)
wushuchu 人气:0想了解springmvc和js前端的数据传递和接收方式(两种)的相关内容吗,wushuchu在本文为您仔细讲解springmvc接收js数据的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springmvc接收js数据,springmvc接收前端数据,springmvc接收数据,下面大家一起来学习吧。
在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)</span> { try { response.setCharacterEncoding("UTF-8"); response.getWriter().write(str); } catch (Exception e) { } } public static <T> String toJSONString(List<T> 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("<option >--请选择城市信息--</option>"); for(var i=0;i<data.length;i++){ $('#custBankArea').append("<option value='"+data[i].id+"'>"+data[i].cityName+"</option>"); } } }); }
2,通过Map传递
controller层实现如下
@RequestMapping("queryProvince") @ResponseBody public Map<String, Object> queryProvince(HttpServletRequest request,HttpServletResponse response){ Map<String, Object> map = new HashMap<String, Object>(); 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.length;i++){ //js实现 //var objs = document.getElementById("cusBankCity") //objs.options.add(new Option(data[i].provinceName) ,data[i].id); //jq实现 $("#cusBankCity").append("<option value='"+data[i].id+"'>"+data[i].provinceName+"</option>"); } } });
加载全部内容