您好,登錄后才能下訂單哦!
這篇文章主要講解了Springmvc和ajax實現前后端交互的方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
springmvc使用@RequestBody來獲取前端的json字符串并轉化為java對象
使用@ReponseBody來將返回的java對象轉換為json形式返回前端
下面是幾個使用springmvc和ajax進行前后端交互的簡單實例
1.傳遞簡單對象:
前端:
$(function(){ $("#btn3").click(function(){ //準備好要發的數組 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"; }
結果:
2.傳遞復雜對象:
1.實體類:
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(){ //準備要發送的數據 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對象轉化為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"; }
結果:
看完上述內容,是不是對Springmvc和ajax實現前后端交互的方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。