Springmvc和ajax實作前後端互動的方法
釋出時間:2020-07-28 15:36:16
來源:億速雲
閱讀:75
作者:小豬
這篇文章主要講解了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 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 subjectList;
private Map 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實作前後端互動的方法有進一步的了解,如果還想學習更多内容,歡迎關注億速雲行業資訊頻道。