java ajax返回 Json 的 幾種方式


原文:https://blog.csdn.net/qq_26289533/article/details/78749057

方式 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() { } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM