目录:
1、Ajax应用场景:
2、Ajax优缺点:
3、一次完整的HTTP请求,一般有七个步骤:
4、什么叫Document对象?
5、Ajax发送异步请求步骤:
6、响应内容为xml数据:
7、测试代码:
1、Ajax应用场景:
Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)
(1)搜索框
(3)分页
2、Ajax优缺点:
(1)优点:①异步交互,增强用户体验
②服务器部分响应,减轻服务器压力,提高性能
(2)缺点:① 不能应用在全部场景
②增多了对服务器的访问次数,给服务器带来压力
3、一次完整的HTTP请求,一般有七个步骤:
①建立TCP连接
②Web浏览器向Web服务器发送请求命令
③Web浏览器发送请求头信息
④Web服务器响应
⑤Web服务器发送响应头信息
⑥Web服务器向浏览器发送数据
⑦Web服务器关闭TCP连接
4、什么叫Document对象?
每个载入浏览器的HTML文档都会成为Document对象,Document对象使我们可以从脚本中对HTML页面的所有元素进行访问。
5、Ajax发送异步请求步骤:
(1)得到XMLHttpRequest
①大多数浏览器支持:var request = new XMLHttpRequest();
②IE 6.0:var request = new ActiveXObject(“Msxml2.XMLHTTP”);
③IE 5.5以及更早版本:var request = new ActiveXObject(“Microsoft.XMLHTTP”);
(2)打开与服务器的连接
XMLHttpRequest.open(method,url,async):
三个参数:
①请求方式:GET、POST
②请求URL:指定服务器的资源
③请求是否为异步:true发送异步请求,false发送同步请求
request.open(“GET”,“/Learn201705/Servlet1”,“true”);
(3)发送请求:
XMLHttpRequest.send(string):
参数:
请求体内容,
①当为GET请求时,其实是没有请求体的,所有参数都拼接在url当中,但必须给出request.send(null),如果不给null可能会造成火狐浏览器无法发送。
②当为POST请求时,在open和send之间加入以下句子:
request.open(“POST”,“true”);
request.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);
request.send(“name=remoa&sex=male”);//发送请求时指定请求体
(4)给异步对象的onreadystatechange事件注册监听器:
①XMLHttpRequest对象有一个onreadystatechange事件,它会在XMLHttpRequest对象的状态readyState属性的值发生变化时被调用。其五种状态分别是:
0:初始化未完成状态,只是创建了XMLHttpRequest对象,还未调用open()方法。
1:请求已开始,open()方法已调用,但还没有调用send()方法。
2:请求发送完成状态,send()方法已调用,也就是接收到头信息了。
3:开始读取服务器响应,也就是接收到响应主体了,但不表示响应结束了。
4:读取服务器响应结束,响应完成。
onreadystatechange事件会在readyState属性状态为1、2、3、4时引发。
②得到XMLHttpRequest对象的状态:
var state = request.readyState;//可能是0、1、2、3、4
我们一般对状态为200且readyState属性值为4时进行处理,即
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
request.responseText //开始做一些事情
}
};
③得到服务器响应的状态码:
var status = request.status;//以数字形式返回HTTP状态码,例如404、500、302
var status = request.statusText;//以文本形式返回HTTP状态码
④得到服务器响应的内容
var content = request.responseText; //获得字符串形式的响应数据
var content = request.responseXML;//获得XML形式的响应数据
⑤getAllResponseHeader():获取所有的响应报头
⑥getResponseHeader():查询响应中的某个字段的值
6、响应内容为xml数据:
①服务器端:
设置响应内容类型:Content-Type,值为text/xml;charset=utf-8
response.setContentType("text/xml;charset=utf-8");
②客户端:
var doc = request.responseXML;//得到的是document对象
7、测试代码:
<%@ 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>Get请求</title>
<script type="text/javascript">
//创建异步对象
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
//IE6.0
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5及更早版本
return new ActiveObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
};
//在文档加载完毕后马上执行
window.onload = function(){
//获取按钮
var btn = document.getElementById("btn");
//给按钮的点击事件注册监听
btn.onclick = function(){
//使用ajax的四步操作
//1、得到异步对象
var request = createXMLHttpRequest();
//2、打开与服务器的连接
request.open("GET","/Learn201705/LoginServlet",true);
//3、发送请求
request.send(null);//不给null值FireFox可能无法发送
//4、给异步对象的onreadystatechange事件注册监听器
request.onreadystatechange = function(){
//双重判断,request的状态为4(服务器响应结束),以及服务器的状态码为200(响应成功)
if(request.status = 200 && request.readyState == 4){
//获取服务器的响应结果
var content = request.responseText;
var h1Content = document.getElementById("show");
h1Content.innerHTML = content;
}
};
};
};
</script>
</head>
<body>
<button id="btn">点击这里</button>
<h1 id="show"></h1>
</body>
</html>
②POST请求页面代码:
<%@ 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>Post请求</title>
<script type="text/javascript">
//创建异步对象
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
//IE6.0
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5及更早版本
return new ActiveObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
};
//在文档加载完毕后马上执行
window.onload = function(){
//获取按钮
var btn = document.getElementById("btn");
//给按钮的点击事件注册监听
btn.onclick = function(){
//使用ajax的四步操作
//1、得到异步对象
var request = createXMLHttpRequest();
//2、打开与服务器的连接
request.open("POST",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//3、发送请求
request.send("account=小邓&password=123456");//不给null值FireFox可能无法发送
//4、给异步对象的onreadystatechange事件注册监听器
request.onreadystatechange = function(){
//双重判断,request的状态为4(服务器响应结束),以及服务器的状态码为200(响应成功)
if(request.status = 200 && request.readyState == 4){
//获取服务器的响应结果
var content = request.responseText;
var h1Content = document.getElementById("show");
h1Content.innerHTML = content;
}
};
};
};
</script>
</head>
<body>
<button id="btn">点击这里</button>
<h1 id="show"></h1>
</body>
</html>
③Servlet代码:
package com.remoa;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
System.out.println("------------doGet------------");
response.getWriter().print("Hello Remoa");
}
protected void doPost(HttpServletRequest request,IOException {
response.setContentType("text/html;charset=utf-8");//将响应编码设置为utf-8
request.setCharacterEncoding("utf-8");//将请求编码设置为utf-8
String account = request.getParameter("account");
String password = request.getParameter("password");
System.out.println("login");
response.getWriter().print("用户" + account + "已登录,密码为" + password);
}
}
④运行结果:
<%@ 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">
<script type="text/javascript" src="<%=request.getContextPath() %>/bootstrap/js/jquery.min.js" ></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/bootstrap/js/bootstrap.min.js" ></script>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/bootstrap/css/bootstrap.min.css" >
<title>用户注册</title>
<script type="text/javascript">
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
//IE6.0
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5及更早版本
return new ActiveObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
};
window.onload = function(){
var account = document.getElementById("account");
account.onblur = function(){
var request = createXMLHttpRequest();
request.open("POST","/Learn201705/ValidateLogin",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("account=" + account.value);
request.onreadystatechange = function(){
if(request.status == 200 && request.readyState == 4){
//获取服务器的响应,判断是否为1,如果为1,则表示已注册,添加内容,如果为0,则表示该账户名未注册,什么都不做
var text = request.responseText;
var spanContent = document.getElementById("accountError");
if(text == 1){
spanContent.innerHTML = "<img src='img/false.png' class='wrong' />用户名已注册!";
}else{
if(account.value.length == 0 || account.value.substring(0,account.value.length) == 0){
spanContent.innerHTML = "<img src='img/false.png' class='wrong'/>输入不能为空或纯空格";
}else{
spanContent.innerHTML = "<img src='img/true.png' />输入正确";
}
}
}
};
};
};
function CheckStrength(pwd){
var leftColor,middleColor,rightColor,colorHtml;
var m = 0;
var Modes = 0;
for(i = 0; i < pwd.length; i++){
var charType = 0;
var t = pwd.charCodeAt(i);
//当字符为数字时,
if(t >= 48 && t <= 57){
charType = 1;
}
//当字符为小写字母时
else if(t >= 97 && t <= 122){
charType = 2;
}
//当字符为大写字母时
else if(t >= 65 && t <= 90){
charType = 4;
}
//为其他字符时
else{
charType = 4;
}
Modes |= charType;//按位或
}
//当密码只由一种元素组成或小于六位,判定为弱
//当密码由两种元素组成且大于等于六位时,判定为中
//当密码由三种元素组成且大于等于六位时,判定为强
//&的用法:两个操作数中的位都为1,结果才为1,否则为0
for(i = 0; i < 4; i++){
if(Modes & 1){
m++;//m为0为无密码,m为1为弱密码,m为2为中密码,m为3为强密码
}
Modes>>>=1;//无符号右移,空位用0补齐
}
//六位以下,都为弱密码
if(0 < pwd.length && pwd.length < 6){
m = 1;
}
switch(m){
//弱密码
case 1:
leftColor="pwd pwd_weak";
middleColor="pwd";
rightColor="pwd";
colorHtml="弱";
break;
//中密码
case 2:
leftColor="pwd pwd_medium";
middleColor="pwd pwd_medium";
rightColor="pwd";
colorHtml="中";
break;
//强密码
case 3:
leftColor="pwd pwd_strong";
middleColor="pwd pwd_strong";
rightColor="pwd pwd_strong";
colorHtml="强";
break;
default:
leftColor="pwd";
middleColor="pwd";
rightColor="pwd";
colorHtml="无";
break;
}
document.getElementById("pwd_weak").className = leftColor;
document.getElementById("pwd_medium").className = middleColor;
document.getElementById("pwd_strong").className = rightColor;
document.getElementById("pwd_medium").innerHTML = colorHtml;
};
$(document).ready(function(){
$("#account").focus(function(){
$(this).parents(".form-group").find("#accountError").html("请输入用户名");
});
$("#password").focus(function(){
$(this).parents(".form-group").find("#passwordError").html("请输入6-16位密码");
});
$("#password").blur(function(){
//密码为空或长度小于6
if($(this).val().length < 6){
if($(this).val() == ""){
$(this).parents(".form-group").find("#passwordError").html("<img src='img/false.png' class='wrong' />密码不能为空");
}else{
$(this).parents(".form-group").find("#passwordError").html("<img src='img/false.png' class='wrong' />密码长度不能少于六位");
}
}
//密码长度大于16
else if($(this).val().length > 16){
$(this).parents(".form-group").find("#passwordError").html("<img src='img/false.png' class='wrong' />密码长度不能大于16位");
}
//正确情况
else{
$(this).parents(".form-group").find("#passwordError").html("<img src='img/true.png' />输入正确");
}
});
$("#checkpassword").focus(function(){
$(this).parents(".form-group").find("#checkError").html("请再次输入以确认密码");
});
$("#checkpassword").blur(function(){
var pwd1 = $("#password").val();
var pwd2 = $(this).val();
//两次密码输入一致
if(pwd1 == pwd2){
$(this).parents(".form-group").find("#checkError").html("<img src='img/true.png' />输入正确");
}
//两次密码输入不一致
else{
$(this).parents(".form-group").find("#checkError").html("<img src='img/false.png' class='wrong' />两次密码输入不一致");
}
});
//检测出错则不能提交
$("#submitBtn").click(function(){
if($(this).parents().find("#account").val()=="" || $(this).parents().find("#password").val()=="" || $(this).parents().find("#checkpassword").val()==""){
alert("请正确填写");
return false;
}
else if($(this).parents().find("img").hasClass("wrong")){
alert("请正确填写");
return false;
}else{
return true;
}
});
});
</script>
<style>
.pwd{
background-color:#F3F3F3;
border:1px solid #D0D0D0;
}
.pwd_font{
color:#BBBBBB;
}
.pwd_weak{
background-color:red;
border:1px solid #BB2B2B;
}
.pwd_medium{
background-color:#FFD35E;
border:1px solid #E9AE10;
}
.pwd_strong{
background-color:#3ABB1C;
border:1px solid #267A12;
}
</style>
</head>
<body>
<div class="container" style="margin-top:2rem">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form class="form-horizontal" method="post" action="RegisterServlet">
<div class="form-group">
<label for="account" class="control-label col-md-3">
账户名:
</label>
<div class="col-md-5">
<input type="text" class="form-control" name="account" id="account" placeholder="请输入账户名"/>
</div>
<div class="col-md-4">
<span id="accountError"></span>
</div>
</div>
<div class="form-group">
<label for="password" class="control-label col-md-3">
密码:
</label>
<div class="col-md-5">
<input type="password" class="form-control" name="password" id="password" placeholder="请输入密码" onKeyUp="CheckStrength(this.value)"/>
<table class="col-md-3 table table-condensed" cellpadding="0" border="0" cellspacing="0" style="margin-bottom:0;margin-top:5px">
<tr align="center">
<td id="pwd_weak" class="pwd"></td>
<td id="pwd_medium" class="pwd pwd_font">无</td>
<td id="pwd_strong" class="pwd"></td>
</tr>
</table>
</div>
<div class="col-md-4">
<span id="passwordError"></span>
</div>
</div>
<div class="form-group">
<label for="checkpassword" class="control-label col-md-3">
确认密码:
</label>
<div class="col-md-5">
<input type="password" class="form-control" name="checkpassword" id="checkpassword" placeholder="请再次输入密码" />
</div>
<div class="col-md-4">
<span id="checkError"></span>
</div>
</div>
<input type="submit" id="submitBtn" class="btn btn-primary col-md-offset-3" style="width:10rem" value="注册"/>
</form>
</div>
</div>
</div>
</body>
</html>
②Servlet代码:package com.remoa;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ValidateLogin")
public class ValidateLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request,IOException {
String account = request.getParameter("account");
List<String> accountList = new ArrayList<String>();
accountList.add("remoa1");
accountList.add("remoa2");
accountList.add("remoa3");
accountList.add("remoa4");
for(Iterator<String> iter = accountList.iterator(); iter.hasNext();){
if(account.equals(iter.next())){
response.getWriter().print("1");
return;
}
}
response.getWriter().println("0");
}
}
③运行结果:
<%@ 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">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/bootstrap/css/bootstrap.min.css" >
<title>获取xml数据</title>
<script type="text/javascript">
//创建异步对象
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
//IE6.0
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5及更早版本
return new ActiveObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
};
//在文档加载完毕后马上执行
window.onload = function(){
//获取按钮
var btn = document.getElementById("btn");
//给按钮的点击事件注册监听
btn.onclick = function(){
//使用ajax的四步操作
//1、得到异步对象
var request = createXMLHttpRequest();
//2、打开与服务器的连接
request.open("GET","/Learn201705/XMLServlet",以及服务器的状态码为200(响应成功)
if(request.status = 200 && request.readyState == 4){
//获取服务器的响应结果
var doc = request.responseXML.documentElement;
var stuArr = doc.getElementsByTagName("student");
var number,name,sex,age;
var text = "<table class='table table-condensed table-bordered table-striped'><tr><th>学号</th><th>姓名</th><th>性别</th><th>年龄</th></tr>";
for(i = 0; i < stuArr.length; i++){
text = text + "<tr>";
number = stuArr[i].getAttribute("number");
try{
text = text + "<td>" + number + "</td>";
}catch(e){
text = text + "<td>/</td>";
}
name = stuArr[i].getElementsByTagName("name");
try{
text = text + "<td>" + name[0].firstChild.nodeValue + "</td>";
}catch(e){
text = text + "<td>/</td>";
}
sex = stuArr[i].getElementsByTagName("sex");
try{
text = text + "<td>" + sex[0].firstChild.nodeValue + "</td>";
}catch(e){
text = text + "<td>/</td>";
}
age = stuArr[i].getElementsByTagName("age");
try{
text = text + "<td>" + age[0].firstChild.nodeValue + "</td>";
}catch(e){
text = text + "<td>/</td>";
}
text = text + "</tr>";
}
text = text + "</table>";
document.getElementById("show").innerHTML = text;
}
};
};
};
</script>
</head>
<body>
<div class="container">
<button id="btn" class="btn btn-primary">点击这里</button>
<h1 id="show"></h1>
</div>
</body>
</html>
<%@ 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">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/bootstrap/css/bootstrap.min.css" >
<title>获取xml数据</title>
<script type="text/javascript">
//创建异步对象
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
//IE6.0
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
//IE5.5及更早版本
return new ActiveObject("Microsoft.XMLHTTP");
}catch(e){
throw e;
}
}
}
};
//在文档加载完毕后马上执行
window.onload = function(){
//获取按钮
var btn = document.getElementById("btn");
//给按钮的点击事件注册监听
btn.onclick = function(){
//使用ajax的四步操作
//1、得到异步对象
var request = createXMLHttpRequest();
//2、打开与服务器的连接
request.open("GET",以及服务器的状态码为200(响应成功)
if(request.status = 200 && request.readyState == 4){
//获取服务器的响应结果
var doc = request.responseXML.documentElement;
var stuArr = doc.getElementsByTagName("student");
var text = "<table class='table table-condensed table-bordered table-striped'><tr><th>学号</th><th>姓名</th><th>性别</th><th>年龄</th></tr>";
var name,number,age;
for(i = 0; i < stuArr.length; i++){
text = text + "<tr>";
var arr = stuArr[i];
number = arr.getAttribute("number");
if(number == null){
number = "/";
}
try{
name = arr.getElementsByTagName("name")[0].textContent;
}catch(e){
name = "/";
}
try{
sex = arr.getElementsByTagName("sex")[0].textContent;
}catch(e){
name = "/";
}
try{
age = arr.getElementsByTagName("age")[0].textContent;
}catch(e){
age = "/";
}
text = text + "<td>" + number + "</td><td>" + name + "</td><td>" + sex + "</td><td>" + age + "</td></tr>";
}
text = text + "</table>";
document.getElementById("show").innerHTML = text;
}
};
};
};
</script>
</head>
<body>
<div class="container">
<button id="btn" class="btn btn-primary">点击这里</button>
<h1 id="show"></h1>
</div>
</body>
</html>
package com.remoa;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/XMLServlet")
public class XMLServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,IOException {
System.out.println("进来------------XMLServlet");
String xml = "<students>"
+ "<student number='3114005847'>"
+ "<name>张三</name>"
+ "<sex>male</sex>"
+ "<age>18</age>"
+ "</student>"
+ "<student number='3114005848'>"
+ "<name>李四</name>"
+ "<sex>male</sex>"
+ "</student>"
+ "<student number='3114005849'>"
+ "<name>王五</name>"
+ "<age>18</age>"
+ "<tel>13334445556</tel>"
+ "</student>"
+ "</students>";
response.setContentType("text/xml;charset=utf-8");
response.getWriter().print(xml);
}
protected void doPost(HttpServletRequest request,IOException {
doGet(request,response);
}
}
③运行结果: