AJAX——初识Ajax、jQuery实现Ajax请求、JSON格式、JackSon工具、熟识Ajax(同步异步、表单序列化) && 练习

Ajax简介

异步交互、局部刷新。其实就是javascript,只是进行了封装。
在这里插入图片描述
比如:看直播,点赞、刷弹幕等;网页分块展示;验证电话号码时提醒消息等

Ⅰ、原生JS实现Ajax请求

在这里插入图片描述
步骤:

1、创建核心对象XMLHttpRequest
2、指定发送请求的相关内容(方式、路径、同异步)
3、发送请求
4、定义onreadystatechange事件(内容改变自动触发),注意全小写
5、当状态为4的时候,获取服务器的响应数据
6、处理数据

一、练习——原生JS实现点赞的功能

video_js.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小视频直播</title>
<script type="text/javascript">
	//点赞的函数
	function like(){
		//创建核心对象
		var xhr = new XMLHttpRequest();
		//指定发送请求的内容(方式、路径、同异步)
		xhr.open("post","videoServlet",true);
		//向servlet发送请求
		xhr.send();
		//定义事件(接收请求,并处理数据)
		xhr.onreadystatechange = function(){
			//获取状态码
			var state = xhr.readyState;
			if(state == 4){//请求已完成,响应已就绪
				var num = xhr.responseText;//获取返回数据responseText、responseXML
				document.getElementById("count").innerText = num;
			}
		}
	}
</script>
</head>
<body>
	<video src="video/小视频直播.mp4" width="500" controls="controls" autoplay="autoplay"></video>
	<br/>
	<input type="button" value="点赞"  onclick="like()">
	点赞数<span style="color: red" id="count"></span><!-- 初始值是个bug没解决,这里主要使用原生JS实现点赞 -->
</body>
</html>

videoServlet.java代码

@WebServlet("/videoServlet")
public class videoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public videoServlet() {
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//每个客户端都共有的数据
		ServletContext sc = getServletContext();
		//获取目前的点赞数(因为可能本客户端是第一个访问用户,存在null的可能,所有用Integer比较合理)
		Integer num = (Integer) sc.getAttribute("num");
		if(num == null) {
			num = 1;
		}else {
			num += 1;
		}
		//放回已经修改的点赞数
		sc.setAttribute("num", num);
		//将点赞数,返回给ajax(out流谁调用返回给谁。没有ajax时,就返回给浏览器)
		PrintWriter out = response.getWriter();
		out.print(num);
		//关闭out流
		out.close();
	}

}

Ⅱ、jQuery版本的Ajax请求

jQuery封装Ajax的常用方法ajax()、get()、post()。

以上三个方法都需要指名响应数据类型

1)text:字符串
2)XML:XML标签类型
3)HTML:HTML标签
4)Script:脚本
5)JSON:JSON类型
6)JSONP:JSON类型,支持跨域访问

一、练习——jQuery的ajax()实现点赞的功能

$.ajax({
	url:"路径",
	type:"get/post",
	data:没有(null)或者有很多{"key1":"valu1","key2":"value2"},
	dataType:"响应数据的类型",
	success:funcation(obj){},
	error:funcation(XMLHttpRequest,textStatus,errorThrom){}
});

注意:
	1、每组值之间用逗号隔开;
	2、前三个请求;后三个响应;
	3、顺序没有要求;
	4、只有dataType有大写。

1、videoServlet一样,省略

2、video_jQuery.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小视频直播</title>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">
	//复习:就绪函数
	$(function(){
		$("[type='button']").click(function(){//这里使用的属性选择器
			$.ajax({
				url:"videoServlet",
				type:"post",
				data:null,
				dataType:"text",//小文本
				success:function(obj){//obj就是服务器响应数据
					$("#count").text(obj);
				},
				error:function(){
					alert("服务器开小差了,请重新刷新页面!!!");
				}
			});
		});
	});
</script>
</head>
<body>
	<video src="video/小视频直播.mp4" width="500" controls="controls" autoplay="autoplay"></video>
	<br/>
	<input type="button" value="点赞">
	点赞数量<span style="color: red" id="count"></span><!-- 初始值是个bug没解决,这里主要使用原生JS实现点赞 -->
</body>
</html>

关于jQuery的相关知识点,如选择器,👉点击👈https://blog.csdn.net/Today_He/article/details/108772926


二、练习——jQuery的get()、post()实现点赞的功能

$.get("路径",{"key1":"valu1","key2":"value2"},function(){},"响应数据的类型");
$.post("路径",{"key1":"valu1","key2":"value2"},function(){},"响应数据的类型");

注意:
1、顺序不可变;
2、不携带数据,就写null;
3、function(){}是成功的回调函数;
4、get()不能发送post请求;post()不能发送个体请求。

1、videoServlet一样,省略

2、video_jQuery_post.jsp代码上面写的post请求,这里也只展示post(),get()一样,只是方法名不同

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小视频直播</title>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">
	//复习:就绪函数
	$(function(){
		$("[type='button']").click(function(){
			$.post("videoServlet",null,function(obj){
				$("#count").text(obj);
			},"text");
		});
	});
</script>
</head>
<body>
	<video src="video/小视频直播.mp4" width="500" controls="controls" autoplay="autoplay"></video>
	<br/>
	<input type="button" value="点赞">
	点赞数量<span style="color: red" id="count"></span><!-- 初始值是个bug没解决,这里主要使用原生JS实现点赞 -->
</body>
</html>

Ⅲ、JSON

在这里插入图片描述
一种特殊格式的字符串(不是类型)

比如使用JSON格式表示:

1、数组							"[1,2,3]"
2、对象							"{\"key1\":value1,\"key2\":value2}"		
	1、value是数字就不需要打双引号了;否则还是用\"\"引起来。
	2、双引号中还是使用双引号(转义之后的)
3、混合(对象+数组)				"[{\"key1\":value1,\"key2\":value2},{\"key1\":value1,\"key2\":value2}]"
4、布尔							直接传true或者false回来即可,不要放在双引号里面……

一、练习——JSON之混合测试

json.html

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试JSON</title>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">
	//复习:就绪函数
	$(function(){
		$.ajax({
			url:"jsonServlet",
			type:"post",
			data:null,
			dataType:"json",//小文本
			success:function(obj){//obj就是服务器响应数据
				/* for(var i=0;i<obj.length;i++){
					console.log(obj[i].name);
				}  */
				$(obj).each(function(index,content){
					console.log(content.name);
				});
			},
			error:function(){
				alert("服务器开小差了,请重新刷新页面!!!");
			}
		});
	});
</script>
</head>
<body>

</body>
</html>

jsonServlet.java

@WebServlet("/jsonServlet")
public class jsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public jsonServlet() {
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String str = "[{\"id\":1,\"name\":\"HBW\",\"age\":17},{\"id\":2,\"name\":\"Mary\",\"age\":17},{\"id\":3,\"name\":\"Tom\",\"age\":18}]";
		PrintWriter out = response.getWriter();
		out.print(str);
		out.close();
	}
}

二、练习——JSON之布尔测试

json_boolean.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试JSON</title>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">
	//复习:就绪函数
	$(function(){
		$.post("jsonServlet",null,function(obj){
			obj ? console.log("真的"):console.log("假的");
		},"json");
	});
</script>
</head>
<body>

</body>
</html>

jsonServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean bol = true;
		PrintWriter out = response.getWriter();
		out.print(bol);
		out.close();
	}

Ⅳ、JackSon

JackSon工具:将常规数据转换成JSON格式的字符串的其中的一种工具。

第一步导包
在这里插入图片描述

第二部使用

一、练习——使用JackSon工具将混合类型的数据,转为JSON,并打印

jackSon_mix.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JackSon工具转换混合类型的数据</title>
</head>
<body>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">
	//复习:就绪函数
	$(function(){
		$.post("jackSonServlet",null,function(obj){
			$(obj).each(function(index,content){
				console.log(content.uname);
			});
		},"json");
		
	});
</script>

</body>
</html>

jackSon_mix.java

@WebServlet("/jackSonServlet")
public class jackSonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public jackSonServlet() {
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Users> list = new ArrayList<Users>();
		list.add(new Users(1,"zs","123"));
		list.add(new Users(2,"ls","123"));
		list.add(new Users(3,"ws","123"));
		ObjectMapper map = new ObjectMapper();
		String json = map.writeValueAsString(list);
		PrintWriter out = response.getWriter();
		out.print(json);
		out.close();
	}

}

Ⅴ、Ajax进阶

一、同步、异步

异步:指的是同一脚本中存在多个Ajax时,不按顺序执行,而是并发执行。默认是异步。

好处:效率高
弊端:如果第二个Ajax需要使用第一个Ajax的结果,那么获取的值就是undefined。

同步:多个Ajax按照顺序执行。

关键字:
async:true(异步,默认)/false(同步)。当然这个关键字只能加在ajax()方法中

一般都使用默认的异步,示例省略……

二、表单序列化

如果向servlet提价的数据过多,一条一条的写,比较复杂。为了解决该问题,就提出了表单序列化。

序列化:将复杂的东西按指定的顺序排列或组合(按照固定格式定义)。这个功能是jQuery的,不要写道原生JS中。
表单对象.serialize()
只是改变提交数据的方式,其余代码都不变

示例

<script type="text/javascript">
	$(function(){
		$("[type='button']").click(function(){
			$.ajax({
				url:"user",
				type:"post",
				//序列化就这里不一样,其他没啥区别(servlet获取方式也不变)
				data:$("#form").serialize(),
				dataType:"json",
				success:function(obj){
					alert("恭喜您注册成功,即将跳转至登录页面!!!");
				},
				error:function(){
					alert("服务器开小查了,请稍后再试!!!");
				}
			});
		});
	});
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈年_H

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值