原生ajax请求与jquery-ajax请求
ajax请求可以在不刷新页面的情况下,请求后台服务器
为了演示的效果,在jsp中添加一段视频,再播放视频的时候请求后台,看效果。
- 普通表单提交返回数据,会刷新页面使得视频会又从头播放。
jsp中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<video src="videos/2.MP4" controls width="500px"></video>
<form action="CommentServlet" method="post">
<input type="text" name="comment" id="c"/>
<input type="submit" value="表单提交">
</form>
<div id="result">
表单提交返回数据:${comment}
</div>
</body>
</html>
servlet中
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String string = request.getParameter("comment");
System.out.println("comment:"+string);
request.setAttribute("comment", string);
request.getRequestDispatcher("ajax.jsp").forward(request, response);
}
利用XMLHttpRequest()对象,进行ajax请求,不会刷新页面
jsp中<%@ page language=”java” contentType=”text/html; charset=UTF-8”
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd">
Insert title here
注:
true: 默认值,异步请求,send方法不会阻塞,其他代码正常执行,异步请求处理响应得用到事件,响应返回时触发此事件,执行对应的函数 xhr.οnlοad=function(){xhr.responseTest;}
最早处理响应返回事件的是xhr.onreadstatechange=function(){xhr.readyState}
发送请求时触发,响应返回时会触发,响应完全返回会触发
状态值变化
xhr 创建时 0
xhr.send 0–>1
xhr. 1–>2 2–>3 (服务器处理时)
3–>4时候表示响应完全返回 ,只需要判断如下就行
if(xhr.readyState==4){}
false: 同步请求 响应没有返回之前,页面代码会暂停,send方法在此期间阻塞。
post请求和get
get: 请求只有请求行和请求头
post: 请求行,请求头,请求体
xhr.open("post",url,true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");//告诉服务器请求体格式为表单格式
xhr.send("请求体内容")//参数名1=参数值&参数名2=参数值
servlet中,直接response回应就好。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String string = request.getParameter("comment");
System.out.println("comment:"+string);
response.getWriter().print(string);
}
jquery中ajax请求
<%@ page language=”java” contentType=”text/html; charset=UTF-8”
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd">
Insert title here
servlet中
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String string = request.getParameter("comment");
System.out.println("comment:"+string);
response.getWriter().print(string);
}
jquery中简写jsp
<%@ page language=”java” contentType=”text/html; charset=UTF-8”
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd">
Insert title here
谢谢!
还没有评论,来说两句吧...