您好,登錄后才能下訂單哦!
這篇文章主要講解了Springmvc和ajax實(shí)現(xiàn)前后端交互的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。
springmvc使用@RequestBody來獲取前端的json字符串并轉(zhuǎn)化為java對象
使用@ReponseBody來將返回的java對象轉(zhuǎn)換為json形式返回前端
下面是幾個使用springmvc和ajax進(jìn)行前后端交互的簡單實(shí)例
1.傳遞簡單對象:
前端:
$(function(){ $("#btn3").click(function(){ //準(zhǔn)備好要發(fā)的數(shù)組 var array=[16,18,56]; var jsonArray=JSON.stringify(array); $.ajax({ "url":"send/three/array.html", "type":"post", "data":jsonArray, "dataType":"text", "contentType":"application/json;charset=UTF-8", "success":function (response) { alert(response); }, "error":function (response) { alert(response); } } ); }); });
后端:
@ResponseBody @RequestMapping("/send/three/array.html") public String testReceiveArrayThreee(@RequestBody List<Integer> array){ for (int i : array) { System.out.println(i); } return "success"; }
結(jié)果:
2.傳遞復(fù)雜對象:
1.實(shí)體類:
public class Student { private Integer stuId; private String studentName; private Address address; private List<Subject> subjectList; private Map<String,String> map; get和set方法省略 } public class Subject { private String subjectName; private Integer subjectScore;} public class Address { private String province; private String city; private String street;}
2.前端ajax:
$(function(){ $("#btn4").click(function(){ //準(zhǔn)備要發(fā)送的數(shù)據(jù) var student={ "stuId":5, "studentName":"tom", "address":{ "province":"海南省", "city":"海南市", "street":"不知道" }, "subjectList":[ { "subjectName":"test", "subjectScore":60 }, { "subjectName":"ssm", "subjectScore":70 } ], "map":{ "k1":"v2", "k2":"v3", "k3":"v4" } }; //json對象轉(zhuǎn)化為json字符串 var requestBody=JSON.stringify(student); $.ajax({ "url":"send/compose/object.json", "type":"post", "data":requestBody, "contentType":"application/json;charset=UTF-8", "dataType":"json", "success":function (response) { console.log(response); }, "error":function (response) { console.log(response); } } ); }); });
后端:
@ResponseBody @RequestMapping("/send/compose/object.html") public String testComposeObject(@RequestBody Student student){ System.out.println(student.toString()); return "success"; }
結(jié)果:
看完上述內(nèi)容,是不是對Springmvc和ajax實(shí)現(xiàn)前后端交互的方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。