JSON
什么是JSON:JSON: JavaScript Object Notation JS对象简谱 , 是一种轻量级的数据交换格式(JavaScript提供)
特点
'[{"name":"周珍珍", "age":18},{"name":"李淑文","age":20}]'
- 数据是以键值对形式(key : value)
- key必须使用双引号包裹
- JSON字符串最外层使用单引号包裹
三种数据格式比对
Java
class Student{private String name;private int age;
}Student stu1 = new Student("周珍珍", 18);
Student stu2 = new Student("李淑文", 20);Student[] stus = {stu1, stu2};
XML
<stus><stu1><name>周珍珍</name><age>18</age></stu1><stu2><name>李淑文</name><age>20</age></stu2>
</stus>
JSON
[{"name":"周珍珍", "age":18},{"name":"李淑文","age":20}]
JSON
- 优点:轻量,相同的数据量下,占用的空间更少
- 缺点:当数据量多之后,可读性变差
XML
- 优点:结构化,可读性高
- 缺点:相同的数据量下,占用的空间更多
JSON与js对象的转化
JSON字符串转js对象
var str = '{"name":"周珍珍", "age":18}';
var jsObj = JSON.parse(str);
console.log(jsObj);
注意:如果出现了不规范的JSON字符串
var str = '{name:"周珍珍", age:18}';
可以使用
eval
函数进行转化var str = '{name:"周珍珍", age:18}'; var jsObj = eval('(' + str + ')'); console.log(jsObj);
JSON字符串转js数组
var arr = '[{"name":"周珍珍", "age":18},{"name":"李淑文","age":20}]';
var jsObj = JSON.parse(arr);
console.log(jsObj);
js对象转JSON字符串
var jsObj = {name:"周珍珍",age:18};var jsonStr = JSON.stringify(jsObj);
console.log(jsonStr);//{"name":"周珍珍","age":18}
js数组转JSON字符串
var jsArr = [{name:"周珍珍",age:18},{name:"李淑文",age:20}];var jsonStr = JSON.stringify(jsArr);
console.log(jsonStr);//[{"name":"周珍珍","age":18},{"name":"李淑文","age":20}]
Java与JSON的转化
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.42</version> </dependency>
Object –> JSONString
将Java对象转化为JSON字符串
Teacher teacher1 = new Teacher("aaa", 23, new Student("zzz", 18));
String json = JSON.toJSONString(teacher1);
System.out.println(json);//{"age":23,"name":"aaa","student":{"age":18,"name":"zzz"}}
将数组转化为JSON字符串
Teacher teacher1 = new Teacher("aaa", 23, new Student("zzz", 18));
Teacher teacher2 = new Teacher("bbb", 27, new Student("lsw", 20));
Teacher[] teachers = new Teacher[]{teacher1, teacher2};
String json = JSON.toJSONString(teachers);
System.out.println(json);
//[{"age":23,"name":"aaa","student":{"age":18,"name":"zzz"}},{"age":27,"name":"bbb","student":{"age":20,"name":"lsw"}}]
将Map转化为JSON字符串
Teacher teacher1 = new Teacher("aaa", 23, new Student("zzz", 18));
Teacher teacher2 = new Teacher("bbb", 27, new Student("lsw", 20));HashMap<String, Object> map = new HashMap<>();
map.put("teacher1", teacher1);
map.put("teacher2", teacher2);String json = JSON.toJSONString(map);
System.out.println(json);
//{"teacher2":{"age":27,"name":"bbb","student":{"age":20,"name":"lsw"}},"teacher1":{"age":23,"name":"aaa","student":{"age":18,"name":"zzz"}}}
将List转化为JSON字符串
Teacher teacher1 = new Teacher("aaa", 23, new Student("zzz", 18));
Teacher teacher2 = new Teacher("bbb", 27, new Student("lsw", 20));ArrayList<Teacher> list = new ArrayList<>();
list.add(teacher1);
list.add(teacher2);String jsonString = JSON.toJSONString(list);
System.out.println(jsonString);
//[{"age":23,"name":"aaa","student":{"age":18,"name":"zzz"}},{"age":27,"name":"bbb","student":{"age":20,"name":"lsw"}}]
JSONString –> Object
JSON字符串转JSONObject对象
String str = "{\"age\":23,\"name\":\"aaa\",\"student\":{\"age\":18,\"name\":\"zzz\"}}";JSONObject json = JSON.toJSON(str);System.out.println(json);//{"age":23,"name":"aaa","student":{"age":18,"name":"zzz"}}
System.out.println(json instanceof String);//trueint age = json.getIntValue("age");//23
String name = json.gteString("name");//aaa
JSON字符串转Java对象
String str = "{\"age\":23,\"name\":\"aaa\",\"student\":{\"age\":18,\"name\":\"zzz\"}}";
Teacher teacher = JSON.parseObject(str, Teacher.class);
System.out.println(teacher);
//Teacher{name = aaa, age = 23, student = Student{name = zzz, age = 18}}
JSON字符串转JSONArray数组对象
String str = "[{\"age\":23,\"name\":\"aaa\",\"student\":{\"age\":18,\"name\":\"zzz\"}},{\"age\":27,\"name\":\"bbb\",\"student\":{\"age\":20,\"name\":\"lsw\"}}]";JSONArray jsonArray = JSON.parseArray(str);System.out.println(jsonArray.get(0));
System.out.println(jsonArray.get(1));//{"student":{"name":"zzz","age":18},"name":"aaa","age":23}
//{"student":{"name":"lsw","age":20},"name":"bbb","age":27}
JSON字符串转Map对象
String str = "{\"teacher2\":{\"age\":27,\"name\":\"bbb\",\"student\":{\"age\":20,\"name\":\"lsw\"}},\"teacher1\":{\"age\":23,\"name\":\"aaa\",\"student\":{\"age\":18,\"name\":\"zzz\"}}}";HashMap<String, Student> map = new HashMap<>();Map<String, JSONObject> map1 = (Map<String, JSONObject>) JSON.parse(str);Set<Map.Entry<String, JSONObject>> entries = map1.entrySet();
for (Map.Entry<String, JSONObject> entry : entries) {Student student = JSON.parseObject(entry.getValue().toString(), Student.class);map.put(entry.getKey(), student);
}Set<Map.Entry<String, Student>> entries1 = map.entrySet();
for (Map.Entry<String, Student> entry : entries1) {System.out.println(entry.getKey());System.out.println(entry.getValue());
}
//teacher2
//Student{name = bbb, age = 27}
//teacher1
//Student{name = aaa, age = 23}
JSON字符转List对象
String str = "[{\"age\":23,\"name\":\"aaa\",\"student\":{\"age\":18,\"name\":\"zzz\"}},{\"age\":27,\"name\":\"bbb\",\"student\":{\"age\":20,\"name\":\"lsw\"}}]";List<Teacher> teachers = JSON.parseArray(str, Teacher.class);
for (Teacher teacher : teachers) {System.out.println(teacher);
}
//Teacher{name = aaa, age = 23, student = Student{name = zzz, age = 18}}
//Teacher{name = bbb, age = 27, student = Student{name = lsw, age = 20}}
Ajax请求
AJAX: Asynchronous JavaScript and XML.
AJAX是一种能够在无需加载整个页面的情况下,能够更新部分网页的技术
-
创建
XMLHttpRequest
对象function getXMLHttpRequest() {let xmlHttp;if (window.XMLHttpRequest) {xmlHttp = new XMLHttpRequest();} else if (window.ActiveXObject) {//IE6及以下版本的浏览器xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}return xmlHttp; }
-
为
XMLHttpRequest
对象绑定onreadystatechange
事件const xmlHttp = getXMLHttpRequest(); //给xmlHttp对象绑定onreadystatechange事件 xmlHttp.onreadystatechange = function () {if (xmlHttp.readyState === 4 && xmlHttp.status === 200) { //响应已就绪let text = xmlHttp.responseText;//获取后端返回的responseText对象(string类型)} }
-
创建/初始化请求
xmlHttp.open("GET","student?action=isRegister&username=aaa",true);//get请求 //--------------------------------------------------------------------------- xmlHttp.open("POST","student",true);//post请求:open方法(请求方式, 请求url,是否异步)
-
发送请求
xmlHttp.send();//get请求 //--------------------------------------------------------------------------- //post请求需要设置请求头信息 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); xmlHttp.send("username=bbb&age=18&sex=male");//post请求
AJAX实战:二级联动
数据库表:provinces
(parent_code
为上一级省市编码,code
为本省市编码)
mapper
层:实现查询所有省份和所有城市
//接口 StudentMapper
public String queryProvinces();
public String queryCities(String parent_code);
//实现类 StudentMapperIpl
@Override
public String queryProvinces() {String sql = "select * from provinces where type = ?";try {List<Province> provinces = DBUtil.query(Province.class, sql, "province");return JSON.toJSONString(provinces);} catch (SQLException | InstantiationException | IllegalAccessException | NoSuchFieldException e) {throw new RuntimeException(e);}
}@Override
public String queryCities(String parent_code) {String sql = "select * from provinces where parent_code = ?";try {List<Province> cities = DBUtil.query(Province.class, sql, parent_code);return JSON.toJSONString(cities);} catch (SQLException | InstantiationException | IllegalAccessException | NoSuchFieldException e) {throw new RuntimeException(e);}
}
controller
层:创建查询所有省份和对应城市的方法
//@WebServlet("/studentServlet")
//StudentController 继承自 BaseServlet
//查询所有省份
public void queryProvinces(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String str = studentMapper.queryProvinces();resp.getWriter().write(str);
}//查询所有城市
public void queryCities(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String parentCode = req.getParameter("parent_code");String str = studentMapper.queryCities(parentCode);resp.getWriter().write(str);
}
前端:实现二级下拉框动态更新
<%--省份--%>
<label for="province">省份:</label>
<select name="province" id="province"></select>
<%--城市--%>
<label for="city">省份:</label>
<select name="city" id="city"></select>
JavaScript:实现加载所有省份和省份变化的onchange
事件
function previewImage(input) {// 检查input是否为File类型if (input.files && input.files[0]) {var reader = new FileReader();// 将图片文件以DataURL的形式读取reader.onload = function (e) {// 将读取到的图片设置为img标签的src属性var preview = document.getElementById('preview');preview.src = e.target.result;// 确保img标签显示新图片preview.style.display = 'block';};// 以DataURL的形式读取图片文件reader.readAsDataURL(input.files[0]);} else {// 如果不支持FileReader,或者没有选择文件,就隐藏img标签var preview = document.getElementById('preview');preview.style.display = 'none';}
}//展示所有省份
function displayProvince() {const xmlHttp = getXMLHttpRequest();//给xmlHttp对象绑定onreadystatechange事件xmlHttp.onreadystatechange = function () {if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {let provinces = JSON.parse(xmlHttp.responseText);console.log(provinces)let province = document.getElementById("province");for (let i = 0; i < provinces.length; i++) {let op = document.createElement("option");op.value = provinces[i].code;op.innerText = provinces[i].name;province.appendChild(op);}}}xmlHttp.open("GET", "studentServlet?action=queryProvinces", true);xmlHttp.send();
}//省份变化的城市信息动态更新(二级联动)
let province = document.getElementById("province");province.onchange = function () {let parent_code = this.value;//获取城市的parent_codeconsole.log(parent_code);const xmlHttp = getXMLHttpRequest();//给xmlHttp对象绑定onreadystatechange事件xmlHttp.onreadystatechange = function () {if (xmlHttp.readyState === 4 && xmlHttp.status === 200) { //响应已就绪let cities = JSON.parse(xmlHttp.responseText);let city = document.getElementById("city");for (let i = 0; i < cities.length; i++) {let op = document.createElement("option");op.value = cities[i].code;op.innerText = cities[i].name;city.appendChild(op);}}}xmlHttp.open("GET", "studentServlet?action=queryCities&parent_code=" + parent_code, true);xmlHttp.send();
}//页面加载主动触发展示所有省份
displayProvince();
tById(“city”);
for (let i = 0; i < cities.length; i++) {
let op = document.createElement(“option”);
op.value = cities[i].code;
op.innerText = cities[i].name;
city.appendChild(op);
}
}
}
xmlHttp.open(“GET”, “studentServlet?action=queryCities&parent_code=” + parent_code, true);
xmlHttp.send();
}
//页面加载主动触发展示所有省份
displayProvince();