代码思路:
- 将数组类型的数据打包成json数据
- 使用JSON.stringfy(json)方法传递json数据
- 引入相关jar包
- 后台java解析json数据
废话不多说,直接上代码:
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js传递数组类型的数据,并在后端解析</title>
<script type="text/javascript" src="/demo/lib/jquery-3.4.1.min.js"></script>
</head>
<body>
<button id="btn">点击传递数组数据到后台</button>
</body>
</html>
<script type="text/javascript">
$(function () {
$("#btn").click(function(){
var array1 =[1,2,3,4,5,6,7,8,9];
var array2=["aaa","bbb","ccc","ddd"];
var str="海关退运洋垃圾大妈向趵突泉吐水盐源县3.6级地震广州地陷3人被困张嘉倪保剑锋合影浙传老师美国失联李阳疑似复婚曲协谴责张云雷世界艾滋病日伦敦";
//拼接json
var jsonData={
"array1":array1,
"array2":array2,
"str":str
};
$.ajax({
url:"/demo/json/receiveJson",
data:{"jsonData":JSON.stringify(jsonData)},//注意要转成JSON.stringify
dataType:"json",
type:"post",
success:function () {
alert("success");
},
error:function () {
alert("error");
}
});
});
});
</script>
后台代码:
package com.example.demo.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.Map;
/**
* @Description TODO
* @Author wangs
* @Date 2019/12/217:05
*/
@Controller
@RequestMapping(value = "/json/")
public class JSonController {
@RequestMapping("toTransJson")
public String toTransJson(){
return "web/transJson";
}
@RequestMapping("receiveJson")
public void receiveJson(String jsonData){//参数注意和前端保持一致
ObjectMapper mapper =new ObjectMapper();
try {
Map<String,Object>map =mapper.readValue(jsonData,Map.class);
List<Integer> array1=(List)map.get("array1");
List<String> array2=(List)map.get("array2");
String str =map.get("str").toString();
System.out.println(array1.toString());
System.out.println(array2.toString());
System.out.println(str);
}catch (Exception e){
e.printStackTrace();
}
}
}
点击页面按钮后,打印输出的结果:
成功!
注意,在pom.xml文件中引入以下依赖:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<!--解析json的jar包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>