java ajax return Json in several ways

Original: https://blog.csdn.net/qq_26289533/article/details/78749057

1. way: from writing code switch Json 

需要  HttpHttpServletRequest request  HttpServletResponse response 

Backstage:

@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()); 
}

 


front end: 

$.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; 
}
}
});

 


Mode 2: @ResponseBody comment 

@ResponseBody 
@RequestMapping (value = "/ haha") 
public Msg {XXX} 
{MSG} return 

$ .ajax ({ 
Data: { 
// userNameOrTel:. $ ( "# Name") Val (), 
// password: $ . ( "#pwd") Val () 
}, 
type: "POST", 
URL: "haha", 
dataType: "JSON", 
// contentType: "file application / JSON; charset = UTF-. 8", // difference here, do not add, or not receive the request parameters 
async: false, // synchronous asynchronous 
Success: function (MSG) { 
Debugger;}}}); 


mode 3: @RestController annotations (such a method in the return values are so Json) 

expanding knowledge ajax request parameter encountered when Json format words must be as follows: 

distal ajax: 

Data: the JSON.stringify ({ 'channelId is': channelId is}), 
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() { } 

 

Guess you like

Origin www.cnblogs.com/jiangfeilong/p/11135055.html