springmvc和js前端的数据传递和接收方式(两种)
在springmvc中controller的结果集可通过json格式传到js前端接受,也可以通过Map传给前端,具体实现如下
1,通过json格式传递
controller层实现如下
@RequestMapping("queryCityInfo") @ResponseBody publicStringqueryCityInfo()throwsException{ StringprovinceId=getString("id"); @SuppressWarnings("rawtypes") ListcityList=personalService.queryCity(provinceId); if(null!=cityList&&cityList.size()>0){ Stringjson=JSONUtils.toJSONString(cityList); super.outStr(json); } returnnull; } protectedvoidoutStr(Stringstr) { try { response.setCharacterEncoding("UTF-8"); response.getWriter().write(str); } catch(Exceptione) { } } publicstaticStringtoJSONString(List list) { JSONArrayjsonArray=JSONArray.fromObject(list); returnjsonArray.toString(); }
js端接受如下
functionselectBankCity(id){ $.ajax({ url:baseAddress+"queryCityInfo.do?provinceId="+id, type:'get', dataType:'json', success:function(data){ $('#custBankArea').empty(); $('#custBankArea').append(""); for(vari=0;i"+data[i].cityName+""); } } }); }
2,通过Map传递
controller层实现如下
@RequestMapping("queryProvince") @ResponseBody publicMapqueryProvince(HttpServletRequestrequest,HttpServletResponseresponse){ Map map=newHashMap (); try{ @SuppressWarnings("rawtypes") ListprovinceList=personalService.queryProvince(); if(null!=provinceList&&provinceList.size()>0){ map.put("province",provinceList); } }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } returnmap; }
js端接受如下
$.ajax({ url:baseAddress+"queryProvince.do", type:"get", success:function(resData){ vardata=resData.province; for(vari=0;i"+data[i].provinceName+""); } } });
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。