日韩精品欧美激情国产一区_中文无码精品一区二区三区在线_岛国毛片AV在线无码不卡_亞洲歐美日韓精品在線_使劲操好爽好粗视频在线播放_日韩一区欧美二区_八戒八戒网影院在线观看神马_亚洲怡红院在线色网_av无码不卡亚洲电影_国产麻豆媒体MDX

spring mvc返回json數(shù)據(jù)格式

時間:2020-06-11 23:45:28 類型:JAVA
字號:    

spring mvc返回json格式需要引入的jar

1.jpg

方法一:

@RequestMapping(value="/testjson")
@ResponseBody
public UserForm testjson(@RequestBody UserForm user){
    // 打印接收的JSON格式數(shù)據(jù)
    System.out.println("uname=" + user.getUname());
    // 返回JSON格式的響應
    return user;
}

對應的前端:

注意加: contentType : "application/json;charset=utf-8"

$.ajax({
    //請求路徑
    url : "/testjson",
    //請求類型
    type : "post",
    //data表示發(fā)送的數(shù)據(jù)
    data : JSON.stringify({
        uname : uname,
        upass : upass,
    }), //定義發(fā)送請求的數(shù)據(jù)格式為JSON字符串
    contentType : "application/json;charset=utf-8",
    //定義回調(diào)響應的數(shù)據(jù)格式為JSON字符串,該屬性可以省略
    dataType : "json",
    //成功響應的結(jié)果
    success : function(data) {
        console.log(data);
        if (data != null) {
            alert("輸入的用戶名:" + data.uname + ",密碼:" + data.upass);
        }
    }
});

方法二:

@RequestMapping(value = "ajaxto")
@ResponseBody
public Map ajaxto(UserForm user,String uname){
    Map<String, Object> map = new HashMap<>();
    map.put("uname", uname);
    map.put("upass", user.getUpass());
    map.put("array", new String[]{"a", "b", "c"});
    return  map;
}

前端:

去: contentType : "application/json;charset=utf-8"

$.ajax({
    //請求路徑
    url : "/ajaxto",
    //請求類型
    type : "post",
    //data表示發(fā)送的數(shù)據(jù)
    data : {
        uname : uname,
        upass : upass,
    }, //定義發(fā)送請求的數(shù)據(jù)格式為JSON字符串
   // contentType : "application/json;charset=utf-8",
    //定義回調(diào)響應的數(shù)據(jù)格式為JSON字符串,該屬性可以省略
    dataType : "json",
    //成功響應的結(jié)果
    success : function(data) {
        console.log(data);
        if (data != null) {
            alert("輸入的用戶名:" + data.uname + ",密碼:" + data.upass);
        }
    }
});

總結(jié):1.如果用JSON.stringify()將對象轉(zhuǎn)成字符串,就需要在ajax請求中指定contentType 為 application/json,且后臺需添加 @RequestBody注解;

   2.如果直接傳json對象則跟上面的相反,不能指定contentType為 application/json,其默認類型是 application/x-www-form-urlencoded 


<