一、JSON
json用来存数据的,后端java代码返回的时json数据(json字符串或者json对象)给前端页面,前端拿到json数据以后解析json将json数据赋值到html标签中,显示到页面上。
servlet返回一个json字符串,通过ajax请求获取到这个json字符串,然后js解析json字符串赋值给标签上数据显示出来。(后端和前端交互的数据是json)
1.1json对象的创建
<script>//在js中定义一个json对象//语法格式:{属性:值,属性2;值2,……}对象 []数组//"" 属性名或者字符串类型的值//键值之间用冒号:分割 多个键值对中间用逗号,隔开//存数据var person = {"name":"zzw","age":18,"sex":"男"};//取数据 对象.键console.log(person.name)console.log(person.age)console.log(person.sex)document.write(person.name)</script>
1.2json数组的创建
数据的本质还是对象
<script>//json数据本身还是对象var stus = [{"sid":1,"stuname":"杨博","age":23},{"sid":2,"stuname":"杨狗","age":18},{"sid":3,"stuname":"博儿","age":10},]console.log(stus[0])document.write(stus[2].stuname + "<br>")for(var key in stus){//遍历的sb 是数组的索引下标console.log(stus[key])document.write(stus[key].sid + " ")document.write(stus[key].stuname + " ")document.write(stus[key].age + "<br>")}//开发时servlet返回的数据是一个list集合,这个集合就是需要用json解析//标准的json数据var objs = {"code":1,"message":"xixida","data":[{"sid":1,"stuname":"杨博","age":23},{"sid":2,"stuname":"杨狗","age":18},]}//碰到{}就是对象 就用对象.键//碰到[]就是数组 就用遍历document.write(objs.code)document.write(objs.message)document.write(objs.data + "<br><br>")for (const listKey in objs.data) {document.write(objs.data[listKey].sid + " ")document.write(objs.data[listKey].stuname + " ")document.write(objs.data[listKey].age + "<br>")}var list = objs.datafor (var i = 0;i < list.length;i++) {document.write(list[i].sid + " ")document.write(list[i].stuname + " ")document.write(list[i].age + "<br>")}</script>
1.3fastjson解析
需要导包fastjson
package com.qfedu.a_fastjson;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import java.util.ArrayList;import java.util.List;/*** @author wodexinhuai* @create 2022-05-17-10:31*/public class Demo1 {public static void main(String[] args) {//将json对象转为json字符串//1.创建对象 并 赋值Student student = new Student(1, "博儿", 23, "F", 165);//2.使用第三方jar包 fastjson.jar包 里面又两个方法toJSONString parseObject//将对象转成json字符串String s = JSON.toJSONString(student);System.out.println(s);//3.将json字符串String s1 = "{'age':100,'height':150,'id':2,'name':'大黄','sex':'公'}";Student student1 = JSON.parseObject(s1, Student.class);System.out.println(student1);//4.将集合转换成json字符串 toJSONString()ArrayList<Student> list = new ArrayList<>();list.add(new Student(1, "艾斯", 23, "F", 185));list.add(new Student(2, "萨博", 20, "F", 188));list.add(new Student(3, "路飞", 18, "F", 180));String s2 = JSON.toJSONString(list);System.out.println(s2);//5.将json数组字符串转成list集合 parseArray(字符串,反射类)String s3 = "[{\"age\":23,\"height\":185,\"id\":1,\"name\":\"艾斯\",\"sex\":\"F\"},{\"age\":20,\"height\":188,\"id\":2,\"name\":\"萨博\",\"sex\":\"F\"},{\"age\":18,\"height\":180,\"id\":3,\"name\":\"路飞\",\"sex\":\"F\"}]";List<Student> students = JSON.parseArray(s3, Student.class);for (Student student2 : students) {System.out.println(student2);}}}
1.4Jackson解析
jackson-annotation
jackson-core - 2.9.10
jackson-databind
package com.qfedu.b_jackson;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import com.qfedu.a_fastjson.Student;import java.io.IOException;import java.util.ArrayList;import java.util.List;/*** @author wodexinhuai* @create 2022-05-17-11:04*/public class Demo2 {public static void main(String[] args) throws IOException {Student student = new Student(1, "博儿", 23, "F", 165);//将对象转为json字符串ObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(student);System.out.println(s);//将json字符串转为对象String s1 = "{\"id\":1,\"name\":\"博儿\",\"age\":23,\"sex\":\"F\",\"height\":165}";Student student1 = objectMapper.readValue(s1, Student.class);System.out.println(student1);//将礼盒转为json字符串ArrayList<Student> list = new ArrayList<>();list.add(new Student(1, "艾斯", 23, "F", 185));list.add(new Student(2, "萨博", 20, "F", 188));list.add(new Student(3, "路飞", 18, "F", 180));String s2 = objectMapper.writeValueAsString(list);System.out.println(s2);//将json字符串转为list集合对象 TypeReference是个接口 泛型是ArrayList<Student> 接口里面的方法不用重写一个{}即可String s3 = "[{\"id\":1,\"name\":\"艾斯\",\"age\":23,\"sex\":\"F\",\"height\":185},{\"id\":2,\"name\":\"萨博\",\"age\":20,\"sex\":\"F\",\"height\":188},{\"id\":3,\"name\":\"路飞\",\"age\":18,\"sex\":\"F\",\"height\":180}]";List<Student> studentList = objectMapper.readValue(s3, new TypeReference<ArrayList<Student>>() {});for (Student student2 : studentList) {System.out.println(student2);}}}
1.5浏览器处理json字符串
后端处理完json数据以后依靠ajax发送给前端页面
前端页面也得会处理json字符串和json对象
JSON.stringify()
<script>var obj = {"name":"zzw","age":20};//将json对象转为json字符串var str = JSON.stringify(obj)document.write(typeof str)//stringdocument.write(str)//{"name":"zzw","age":20}</script>
1.6json字符串转为json对象【重点】
二、AJAX
通过ajax进行请求前端资源,处理完以后,返回数据给ajax
1.网页中发生一个事件(页面加载,按钮点击)
2.由JavaScript创建XMLHttpRequest对象
3.XMLHttpReaquest对象 像web 服务器发送请求
4.服务器处理该请求
5.服务器将响应发送回网页
6.由JS读取响应
7.由JS执行正确的动作(比如更新页面)
ajax.html
<body><div id="div1"></div><!-- 点击按钮 执行ajax方法 ajax()方法里是向servlet发送请求--><button onclick="ajax()">点击</button></body><script>function ajax(){//1.使用js中ajax核心类对象var xhttp = new XMLHttpRequest()//2.建立连接 向服务器发送请求 固定写法xhttp.open("GET","AjaxServlet?username=sb&password=123");xhttp.send();//是响应处于就绪的一个事件 servlet给响应了 ,响应以后又回到ajax//告知ajax,servlet的响应已经准备就绪,ajax接下来可以操作了xhttp.onreadystatechange = function (){//==4 请求已完成且响应已就绪//==200 okif(xhttp.readyState == 4 && xhttp.status == 200){//如果执行if语句 说明 请求和响应是正常的//开始处理响应的数据 responseText 以字符串返回响应的数据console.log()var div1 = document.getElementById("div1")div1.innerText = xhttp.responseText}}}//整个流程:ajax发送请求servlet,Servlet返回一个json数据给ajax//代码走到这一步,ajax发送请求到服务器servlet//servlet返回数据给ajax 下午讲</script>
AjaxServlet
@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//ajax请求AjaxServlet 带着数据过来的response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");String username = request.getParameter("username");String password = request.getParameter("password");// System.out.println(username);// System.out.println(password);//服务器将响应发送到浏览器,发送的是json字符串response.getWriter().write("hello:" + username + ",密码:" + password);}
三、Jquery中的ajax的使用
Jquery是封装了js。写法变得简单
