方式 1. : 自写代码转 Json
需要 HttpHttpServletRequest request HttpServletResponse response
后台 :
-
@RequestMapping(value=
"/haha")
-
-
public string xxx { HttpHttpServletRequest request,HttpServletResponse response}
-
{ JSONObject json =
new JSONObject();
-
json.put(
"result",
" success")
-
response.setCharacterEncoding(
"utf-8");
-
response.setContentType(
"application/json;charset=utf-8");
-
PrintWriter out =
null;
-
out = response.getWriter();
-
out.write(json.toString());
-
}
前端 :
-
$.ajax({
-
data : {
-
// userNameOrTel: $("#user").val(),
-
// password: $("#pwd").val()
-
},
-
type :
"post",
-
url :
"admin/login/",
-
dataType :
"json",
-
contentType :
"application/json;charset=utf-8",
-
async :
false,
//同步 异步
-
success : function(data) {
-
debugger;
-
}
-
}
-
});
方式 2: @ResponseBody 注解
-
@ResponseBody
-
@RequestMapping(value=
"/haha")
-
public Msg xxx {}
-
{
return msg }
-
-
$.ajax({
-
data : {
-
// userNameOrTel: $("#name").val(),
-
// password: $("#pwd").val()
-
},
-
type :
"post",
-
url :
"haha",
-
dataType :
"json",
-
//contentType : "application/json;charset=utf-8", // 区别在这里,不要加,不然接收不到请求参数
-
async :
false,
//同步异步
-
success : function(msg) {
-
debugger;}}});
方式 3 : @RestController 注解 (此类里的所以方法返回值都是 Json)
拓展知识 当遇到 ajax 请求参数必须是Json 格式的话如下 :
前端 ajax :
-
data:JSON.stringify({
'channelId':channelId}),
-
success:function(data){
-
alert(data.channelId);
-
},
-
-
contentType:
'application/json;charset=utf-8'
后台 :
@RequestMapping(value="/login",produces="application/json;charset=UTF-8") @ResponseBody public String test2() { }