springmvc和js前端的数据传递和接收方式(两种)
在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>"); } } });
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)