JavaScript对象XMLHttpRequest是整个Ajax技术的核心,它提供了异步发送请求的能力
方法名 | 说 明 |
open(method,URL,async) | 建立与服务器的连接 method参数指定请求的HTTP方法,典型的值是GET或POST URL参数指定请求的地址 async参数指定是否使用异步请求,其值为true或false |
send(content) | 发送请求 content参数指定请求的参数 |
setRequestHeader(header,value) | 设置请求的头信息 |
常用属性 onreadystatechange:指定回调函数
readystate: XMLHttpRequest的状态信息
就绪状态码 | 说 明 |
0 | XMLHttpRequest对象没有完成初始化 |
1 | XMLHttpRequest对象开始发送请求 |
2 | XMLHttpRequest对象的请求发送完成 |
3 | XMLHttpRequest对象开始读取响应,还没有结束 |
4 | XMLHttpRequest对象读取响应结束 |
常用属性 status:HTTP的状态码
状态码状态码 | 说 明 |
200 | 服务器响应正常 |
400 | 无法找到请求的资源 |
403 | 没有访问权限 |
404 | 访问的资源不存在 |
500 | 服务器内部错误 |
responseText:获得响应的文本内容
responseXML:获得响应的XML文档对象
下面代码演示以下效果:
1.ajax基础流程(登录)
2.json(ajax传递集合数据)
3.在上面的基础上加鼠标离开移上去事件
4.自动补全
login.sjp
<%@ 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>
<script type="text/javascript">
function login() {
//接收用户名
var uname = document.getElementById("uname").value;
var upwd = document.getElementById("upwd").value;
//声明一个xmlhttpRequest对象
var xmlhttp;
try{
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
catch(e){
xmlhttp=new XMLHttpRequest();
}
//连接服务器
xmlhttp.open("post","LoginServlet?uname="+uname+"&upwd="+upwd,true);
//设置请求头信息
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//设置回调函数
xmlhttp.onreadystatechange=function(){
//判断请求响应结束
if(xmlhttp.readyState==4){
//服务器正常
if(xmlhttp.status==200){
//接收响应的数据
var str = xmlhttp.responseText;
if(str=="ok"){
document.getElementById("sp").innerHTML="✔";
}else{
document.getElementById("sp").innerHTML="×";
}
}
}
}
//发送
xmlhttp.send(null);
}
</script>
</head>
<body>
<form action="">
用户名:<input type="text" id="uname"><br>
密码:<input type="password" id="upwd" onblur="login()"><br>
<span id="sp"></span>
<input type="submit" value="登录">
<input type="reset" value="重置">
</form>
</body>
</html>
LoginServlet
package com.zking.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("来了 老弟");
//接收数据
String uname = req.getParameter("uname");
String upwd = req.getParameter("upwd");
System.out.println("uname:"+uname);
System.out.println("upwd:"+upwd);
resp.setCharacterEncoding("utf-8");
//获取响应的 输出流
PrintWriter out = resp.getWriter();
if("admin".equals(uname) && "123".equals(upwd)) {
out.print("ok");
}else {
out.print("no");
}
out.close();
}
}
index.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>
<!-- 引用jQuery库 -->
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
<script type="text/javascript">
function over(obj) {
obj.style.backgroundColor='green';
}
function out(obj) {
obj.style.backgroundColor='white';
}
function check_str() {
//声明一个xmlhttpRequest对象
var xmlhttp;
try{
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
catch(e){
xmlhttp=new XMLHttpRequest();
}
//连接服务器
xmlhttp.open("post","IndexServlet",true);
//设置请求头信息
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//设置回调函数
xmlhttp.onreadystatechange=function(){
//判断请求响应结束
if(xmlhttp.readyState==4){
//服务器正常
if(xmlhttp.status==200){
//接收响应的数据
var str = xmlhttp.responseText;
alert(str);
//把字符串解析为集合
var slist = eval(str);
var tstr = "<table class="table table-hover" border='1' align='center'>";
//遍历集合
for(var i=0;i<slist.length;i++){
tstr+="<tr onmouseover='over(this)' onmouseout=out(this);>";
tstr+="<td>";
tstr+=slist[i].sid;
tstr+="</td>";
tstr+="<td>";
tstr+=slist[i].sname;
tstr+="</td>";
tstr+="<td>";
tstr+=slist[i].sex;
tstr+="</td>";
tstr+="<td>";
tstr+=slist[i].sinfo;
tstr+="</td>";
tstr+="</tr>";
}
tstr +="</table>";
document.getElementById("d").innerHTML=tstr;
}
}
}
//发送
xmlhttp.send(null);
}
</script>
</head>
<body>
<form align="center" action="">
<input type="text" id="str" onblur="check_str()">
</form>
<div id="d">
</div>
</body>
</html>
index2.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>
<script type="text/javascript">
function check_str(obj) {
var s = obj.value;
//声明一个xmlhttpRequest对象
var xmlhttp;
try{
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
catch(e){
xmlhttp=new XMLHttpRequest();
}
//连接服务器
xmlhttp.open("post","IndexServlet?str="+s,true);
//设置请求头信息
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//设置回调函数
xmlhttp.onreadystatechange=function(){
//判断请求响应结束
if(xmlhttp.readyState==4){
//服务器正常
if(xmlhttp.status==200){
//接收响应的数据
var str = xmlhttp.responseText;
var nlist = eval(str);
var nstr = "<ul>";
//遍历集合
for(var i=0;i<nlist.length;i++){
nstr += "<li>";
nstr += nlist[i].ntitle;
nstr += "</li>";
}
nstr += "</ul>";
//赋值到div
document.getElementById("d").innerHTML=nstr;
}
}
}
//发送
xmlhttp.send(null);
}
</script>
</head>
<body>
<form align="center" action="">
<input onkeyup="check_str(this)" type="text" id="str" >
</form>
<div id="d" style="margin-left: 200px">
</div>
</body>
</html>
IndexServlet.java
package com.zking.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.zking.dao.NewsDao;
import com.zking.entity.News;
public class IndexServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("来了");
String s = req.getParameter("str");
if(s==null) {
s = "";
}
System.out.println("接收关键字:"+s);
ArrayList<News> nlist = new NewsDao().getByLike(s);
//把集合转换为字符串
String str = JSON.toJSONString(nlist);
//设置响应编码
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.print(str);
out.flush();
out.close();
}
}