java前后端用json传值_前后端——json的传值与接收(springMvc)
原標題:前后端——json的傳值與接收(springMvc)
前端傳值:
通過將要傳輸的數據封裝為json,然后再通過ajax接收:
JSON.stringify(data)
1
后端接收值只需要通過一句話即可實現:
@RequestBody String param
1
此處的param就是你所接收的值
具體如何解析:
JSONObject jo=new JSONObject();
List parseArray = jo.parseArray(param, Map.class);
System.out.println("parseArray="+parseArray);
1
2
3
只需要這幾句話即可
下面舉一個小demo:
前端:
$("#excelOutput").click(function(){
console.log("傳出的數據="+JSON.stringify(excelData))
$.ajax({
url : "${App_Path}/excel",
data:JSON.stringify(excelData),
type : "post",
dataType: "json",
contentType: "application/json; charset=utf-8",//此處不能省略
success : function(data) {
alert("success")
},
error:function(){
alert("fail")
}
});
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
后端:
@ResponseBody
@RequestMapping(value = "/excel", method = RequestMethod.POST)
public Msg excel(@RequestBody String param) throws Exception {
System.out.println("param="+param);
JSONObject jo=new JSONObject();
List parseArray = jo.parseArray(param, Map.class);
System.out.println("parseArray="+parseArray);
for (Map map:parseArray) {
System.out.println("map="+map);
}
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
以上就是傳值與接收值的具體情況,當然也可以封裝一個bean對象,直接轉為bean也行
下面繼續拓展一個springMvc的知識,如果前端傳值是通過這種方式:
$("#excelOutput").click(function(){
console.log("傳出的數據="+JSON.stringify(excelData))
$.ajax({
url : "${App_Path}/excel/"+result,
data:JSON.stringify(excelData),
type : "post",
dataType: "json",
contentType: "application/json; charset=utf-8",//此處不能省略
success : function(data) {
alert("success")
},
error:function(){
alert("fail")
}
});
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上面傳了兩個值,一個是result,一個是excelData,看后端怎么處理:
@ResponseBody
@RequestMapping(value = "/excel/{result}", method = RequestMethod.POST)
public Msg excel(@RequestBody String param,@PathVariable String result) throws Exception{
System.out.println("param="+param);
System.out.println("result="+result);//result就是url : "${App_Path}/excel/"+result中的result
JSONObject jo=new JSONObject();
List parseArray = jo.parseArray(param, Map.class);
System.out.println("parseArray="+parseArray);
for (Map map:parseArray) {
System.out.println("map="+map);
}
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
springMvc如何和前端頁面交互,傳輸json數據
責任編輯:
總結
以上是生活随笔為你收集整理的java前后端用json传值_前后端——json的传值与接收(springMvc)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java自定义标签 map_基于Spri
- 下一篇: s3c2440移植MQTT