首頁  >  文章  >  web前端  >  介紹Spring中ajax與後台傳輸資料的幾種方式

介紹Spring中ajax與後台傳輸資料的幾種方式

coldplay.xixi
coldplay.xixi轉載
2020-12-04 16:26:327731瀏覽

ajax欄位介紹與背景傳送資料的方法

介紹Spring中ajax與後台傳輸資料的幾種方式

推薦(免費):ajax

最近寫ajax與後台傳輸資料的時候碰到了一個問題,我想ajax以json的方式把資料傳送個後台,後台用map的形式接收,然後也以map的形式傳回數據。可是一直碰到前台報(*)(@415 Unsupported media type) 不支援媒體類型錯誤,然後經過查閱資料終於解決了。這裡總結下關於ajax與後台傳輸資料的幾種方式,上面問題的解決方法在本文最後。


1.把資料放到url中傳遞
js:
<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById/"+id,//参数放在url中
success:function(data){ alert(data);
},
error:function(xhr, textStatus, errorThrown) {
}
});
</code>
後台:

e03b848252eb9375d56be284e690e873ffbe95d20f3893062224282accb13e8f

@RequestMapping(value = "getPeopleById/{id}")
@ResponseBody
    public Map14bd1badcdee783757181db757c9943f getPeopleById(@PathVariable("id") int id) {
        //@PathVariable("id") 如果参数名与url定义的一样注解可以不用定义("id")
        System.out.println(id);
        Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
        return map;
    }
}

1cd55414ff5abdfea5dd958e7e547fddbc5574f69a0cba105bc93bd3dc13c4ec

2.把資料放到data中
js:
<code>
var id = $("#id").val();
$.ajax({
type: "POST",
url: "/IFTree/people/getPeopleById",
data: {id:id},
success:function(data){ alert(data.result);
},
error:function(xhr, textStatus, errorThrown) {
}
});
</code>
後台(兩個方式):

e03b848252eb9375d56be284e690e873ffbe95d20f3893062224282accb13e8f

@RequestMapping(value = "getPeopleById")
@ResponseBody
public Map14bd1badcdee783757181db757c9943f getPeopleById(HttpServletRequest request,HttpServletResponse response) {
    int id = Integer.valueOf(request.getParameter("id"));
    Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
    return map;
}

1cd55414ff5abdfea5dd958e7e547fddbc5574f69a0cba105bc93bd3dc13c4ec


@RequestMapping(value = "getPeopleById")
@ResponseBody
public Map14bd1badcdee783757181db757c9943f getPeopleById(HttpServletRequest request,HttpServletResponse response) {
    int id = Integer.valueOf(request.getParameter("id"));
    // 这里得到的都是字符串得转换成你需要的类型
    Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
    return map;
}

1cd55414ff5abdfea5dd958e7e547fdd

3.以json傳輸(就是開頭說的情況)
#js(包含一些常見的ajax參數解釋):
<code>
var id = $("#id").val();
$.ajax({
type: "POST",//请求类型
timeout:10000,  //设置请求超时时间(毫秒)
async:ture,//是否为异步请求
cache:false,//是否从浏览器缓存中加载请求信息。
url: "/IFTree/people/getPeopleById",
contentType: "application/json;charset=UTF-8",//提交的数据类型
data: JSON.stringify({id:id}),//这里是把json转化为字符串形式
dataType: "json",//返回的数据类型
success:function(data){
$("#name").val(data.result.name);
},
error:function(xhr, textStatus, errorThrown) {
}
});
});
</code>
後台:

1417fd9caae40516c8185eb949b251edffbe95d20f3893062224282accb13e8f

@RequestMapping(value = "getPeopleById", produces = "application/json")
@ResponseBody
public Map14bd1badcdee783757181db757c9943f getPeopleById(@RequestBody Map14bd1badcdee783757181db757c9943f body){
    System.out.println(""+body.get("id"));
    People people = peopleService.getPeopleById(Integer.valueOf((String)body.get("id")));
    Map14bd1badcdee783757181db757c9943f map = new HashMap14bd1badcdee783757181db757c9943f();
    map.put("result", people);
    return map;
}

1cd55414ff5abdfea5dd958e7e547fddbc5574f69a0cba105bc93bd3dc13c4ec

詳解:

@RequestBody
此註解首先讀取request請求的正文數據,然後使用預設配置的HttpMessageConverter進行解析,把數據綁定要物件上面,然後再把物件綁定到controllor中的參數上。
@ResponseBody
該註解也是一樣的用於將Controller的方法返回的對象,通過的HttpMessageConverter轉換為指定格式後,寫入到Response對象的body資料區。

Srping mvc .xml(設定轉換器)

ffbe95d20f3893062224282accb13e8f

 266dae442ac9dc95e3bdec99752e3b4d
 584454ffd05c6f0e3c55641435afbafd
    4d2d13b32b6824d433e20957bf031c9c
        0efe1b6b91208fe6ccb37533ee972a52
        4309a73696dbaeac0ddd115cebb6f9b7
            9cfc82ad645e238cfb23844fcc566fb0
            b15467429256a47420d73a292704d15c
            4fd24be84f9bb50bd43e1c13351e6665
            b6b7f77ea6dcfce4539ab4f516be1876
            05da36058a5ae95ab9385e514bd64d98
            21a4cbd21ee44ffbefb7b42e6a338a11
                d0e6ed04ce081f36fe4ad23a6e2f195d
                    4309a73696dbaeac0ddd115cebb6f9b7
                        8487820b627113dd990f63dd2ef215f3application/json;charset=UTF-84b175f9a50d57c75316becd702e959dc
                    17e5453f22e09a7f163b2d4ce32c48b7
                dde4123f2ed5a21d0bae333af89830f9
            4bb0e59fd50cbfe6f6ce2215b9d9424341a073a833a1192b911b28010fe7d5f7
        17e5453f22e09a7f163b2d4ce32c48b7
    dde4123f2ed5a21d0bae333af89830f9
4bb0e59fd50cbfe6f6ce2215b9d94243

1cd55414ff5abdfea5dd958e7e547fdd
ByteArrayHttpMessageConverter: 負責讀取取二進位格式的資料和寫出二進位格式的資料;
StringHttpMessageConverter:   負責讀取字串格式的資料和寫出二進位格式的資料;
ResourceHttpMessageConverter :負責讀取資源檔案和寫出資源檔案資料;
FormHttpMessageConverter:       負責讀取form提交的資料
MappingJacksonHttpMessageConverter:  格式在讀取和寫入jsonpingJacksonHttpMessageConverter
:  格式的資料;SouceHttpMessageConverter
:                   負責讀取與寫入xml 中javax.xml.transform.Source定義的資料;##Jb2Root#Jaxb2Root. xml 標籤格式的資料;
AtomFeedHttpMessageConverter:              負責讀取與寫入Atom格式的資料;
RssChannelHttpMessageConverter 專案裡面我用到的只有json轉換器,所以要導入關於json的套件(maven):

<code>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
</code>

同樣controller中參數也能以實體類別的方式接收數據,

開始一直報(415 Unsupported media type)的錯誤是因為設定檔沒有寫對也沒導入相應的包。

如果有哪裡不足或錯誤的地方望提出,謝謝
_

想了解更多程式設計學習,請關注
php培訓

欄目!
#

以上是介紹Spring中ajax與後台傳輸資料的幾種方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jianshu.com。如有侵權,請聯絡admin@php.cn刪除