前端ajax传递json数据给后端并接受后端的数据(需要导入jquery):
var jsonObj = {"user_name":"sss","password":"123"};
$.ajax({
contentType:"application/x-www-form-urlencoded; charset=utf-8",
type:"post",
url:"/test1",
data:jsonObj,
success:function(data){
alert("success!!! "+ JSON.stringify(data));
},
error:function(e){
alert("error");
},
});
json字符串与对象互转:
json字符串----->json对象
使用JSON.parse()函数
json对象------>json字符串
使用JSON.stringify()
后端Controller获取前端传过来的值并返回数据到前端:
@Controller
public class Interactive {
@RequestMapping(value = "/test1" ,method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> test1(HttpServletRequest request, HttpServletResponse response){
Map<String,Object> map = new HashMap<String, Object>();
String name = request.getParameter("user_name");
String password = request.getParameter("password");
System.out.println(name+" "+password);
map.put("result","返回成功");
return map;
}
}