赞
踩
使用ajax传参数,发现后台获取不到数据
value2={'key21':'value21','key22':'value22'}; post_data = {'key1':'value1','key2':value2}; $("#funDiv1").bind("click",function(){ $.ajax({ type : 'post', url : 'ajaxTest.do', data : post_data, dataType : 'text',//若为json,无法接受字符传返回值 success : function(data){ alert("success"); console.log(data); } }); });
key1可以获取到值,key2为空,原因是key2为json对象,后台无法解析,
后台springMVC
@ResponseBody @RequestMapping(value="/ajaxTest.do",produces="application/json;charset=utf-8",method={RequestMethod.POST,RequestMethod.GET}) public String test2(HttpServletRequest request,String key1,String key2){ System.out.println(key1); System.out.println(key2); return "test2_result"; }
解决方法:
前端把json对象转为字符串,后台再解析
JSON.stringify(value2)
后台解析,需要导包,
@ResponseBody @RequestMapping(value="/ajaxTest.do",produces="application/json;charset=utf-8",method={RequestMethod.POST,RequestMethod.GET}) public String test2(HttpServletRequest request,String key1,String key2){ System.out.println("test2"); System.out.println(key1); System.out.println(key2); try{ Map map = JSONObject.fromObject(key2); System.out.println(map.get("key21")); }catch(Exception e){ e.printStackTrace(); } return "test2_result"; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。