Ajax异步数据交互
大约 16 分钟
Ajax 简介
Ajax
- Ajax(Asynchronous JavaScript and XML,异步 JavaScript 和 XML)并不是一项新的技术,它产生的主要目的是用于页面的局部刷新,利用这样的技术可以有效的提升页面的响应速度,
- Ajax 技术的最早使用者是 Google(谷歌),例如,GoogleMaps 就大量地应用了 Ajax 技术。随后的 Yahoo(雅虎)Amazon(亚马逊)也陆续开始应用此技术,而到了现在几乎所有的互联网项目中都存在有 Ajax 技术应用,其不仅是前端开发人员必备的技能,也是后端架构人员的必备技能。
WEB 页面展示
在传统的 WEB 项目开发中,只要用户发出了请求,那么就会根据用户的请求进行相应的数据库查询,最终形成完整的显示页面,如果说现在有一个页面的查询需要同时涉及到五张数据表的处理,那么所生成的页面时间也会相应的增加。
Ajax 局部更新
当一个页面显示完成之后,那么肯定会需要进行页面的操作那么就有可能需要进行指定部分的数据更新,传统的做法采用的是重新加载整个页面的形式完成的,而如果使用的是 Aiax 则只会进行部分内容的更新,很明显这样部分更新的处理机制可以明显的实现整个 WEB 程序性能的提升。
XMLHttpRequest
XMLHttpRequest
- Ajax 本身是一门综合性的技术,其主要应用包含了 HTMLJavaScript、XML、DOM、XMLHttpRequest 等页面技术但是在这之中最重要的就是 XMLHttpRequest 对象。
- 在 Ajax 中主要是通过 XMLHttpRequest 对象处理发送异步请求和回应的,此对象最早是在 IE 5 中以 ActiveX 组件的形式出现的-直到 2005 年之后才被广泛地使用,在 XMLHttpRequest 类之中存在有许多的操作属性与处理函数,利用这些结构就可以实现 Ajax 请求与响应数据的接收处理
readyState
- 在 XMLHttpRequest 类中最重要的一个属性就是 readyState 该属性描述了不同的 Aiax 的数据处理状态,开发者要根据不同的状态进行不同的处理操作,五种具体的取值定义如下
- 0:请求没有发出(在调用 open()函数之前)。
- 1:请求已经建立但还没有发出(在调用 send()函数之前)
- 2:请求已经发出正在处理之中(这里通常可以从响应得到内容头部)
- 3:请求已经处理,正在接收服务器的信息,响应中通常有部分数据可,但是服务器还没有完成响应。
- 4:响应已完成,可以访问服务器响应并使用它
Ajax 基础开发
Ajax 新支持
1、
<html>
<head>
<title>沐言科技:www.yootk.com</title>
<base href="<%=basePath%>">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="jquery/Message_zh_CN.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<link href="bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
window.onload = function() { // 动态事件绑定
document.getElementById("sendBut").addEventListener("click", function() {
msg = document.getElementById("msg"); // 表单的参数内容
if (msg) { // msg参数有内容
xmlHttpRequest = new XMLHttpRequest(); // 获取Ajax操作对象
if (xmlHttpRequest.withCredentials) { // 当前浏览器是否支持有Ajax操作
alert("对不起,您的浏览器不支持Aajx处理操作!");
} else { // 现在支持有Ajax的处理操作
xmlHttpRequest.open("post", "echo.action"); // 建立通讯连接
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置头信息
xmlHttpRequest.onprogress = function (env) { // 处理的进度
document.querySelector("#statusDiv").innerHTML +=
"<p>正在进行数据处理操作,处理进度:" + (env.loaded / env.total) * 100 + "</p>"
}
xmlHttpRequest.onload = function (env) { // 接收响应数据
echoMsg = xmlHttpRequest.responseText; // 响应数据
pElement = document.createElement("p");
pElement.appendChild(document.createTextNode(echoMsg));
document.getElementById("echoDiv").appendChild(pElement);
document.getElementById("msg").value = "";
}
xmlHttpRequest.send("message=" + msg.value); // 发送请求参数
}
}
}, false);
}
</script>
</head>
<body>
<div> </div>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<strong><img src="images/logo.png" style="height: 30px;"> Ajax异步数据交互</strong>
</div>
<div class="panel-body">
<div class="panel panel-success">
<div class="panel-heading">
<strong><span class="glyphicon glyphicon-comment"/> 异步数据回显</strong>
</div>
<div class="panel-body" id="echoDiv"></div>
<div class="panel-footer" id="statusDiv"></div>
</div>
<form action="import.action" class="form-horizontal" id="myform" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group" id="fileDiv">
<label class="col-md-2 control-label" for="msg">请输入信息:</label>
<div class="col-md-5">
<input type="text" name="msg" id="msg" class="form-control input-sm" placeholder="请输入要发送的消息...">
</div>
<div class="col-md-4" id="msgMsg">*</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<button type="button" class="btn btn-sm btn-primary" id="sendBut"><span class="glyphicon glyphicon-open"/> 发送</button>
<button type="reset" class="btn btn-sm btn-warning"><span class="glyphicon glyphicon-retweet"/> 重置</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="panel-footer">
<div style="text-align:right;">
<strong>沐言科技(www.yootk.com) —— 新时代软件教育领导品牌</strong>
</div>
</div>
</div>
</div>
</body>
</html>
2、
<html>
<head>
<title>沐言科技:www.yootk.com</title>
<base href="<%=basePath%>">
<script type="text/javascript" src="js/json3.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="jquery/Message_zh_CN.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
window.onload = function() { // 动态事件绑定
loadProvinceData(); // 调用省份信息加载函数
}
function loadProvinceData() { // 加载省份数据信息
xmlHttpRequest = new XMLHttpRequest(); // 获取Ajax操作对象
if (xmlHttpRequest.withCredentials) { // 当前浏览器是否支持有Ajax操作
alert("对不起,您的浏览器不支持Aajx处理操作!");
} else { // 现在支持有Ajax的处理操作
xmlHttpRequest.open("post", "province.action"); // 建立通讯连接
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置头信息
xmlHttpRequest.onload = function (env) { // 接收响应数据
jsonText = xmlHttpRequest.responseText; // 响应数据
provinceJsonObject = JSON.parse(jsonText); // 进行文本数据的节诶系
for (x = 0; x < provinceJsonObject.length; x ++) {
optionElement = document.createElement("option"); // 创建元素
optionElement.setAttribute("value",provinceJsonObject[x].pid);
optionElement.appendChild(document.createTextNode(provinceJsonObject[x].title));
document.getElementById("province").appendChild(optionElement);
}
}
xmlHttpRequest.send(); // 发送请求参数
}
}
</script>
</head>
<body>
<div> </div>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<strong><img src="images/logo.png" style="height: 30px;"> 【AJAX + JSON】级联菜单开发实例</strong>
</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-1">省份:</div>
<div class="col-md-5">
<select name="province" id="province" class="form-control">
<option value="">============= 请选择快递配送省份 =============</option>
</select>
</div>
<div class="col-md-1">城市:</div>
<div class="col-md-5">
<select name="city" id="city" class="form-control">
<option value="">============= 请选择快递配送城市 =============</option>
</select>
</div>
</div>
</div>
<div class="panel-footer">
<div style="text-align:right;">
<strong>沐言科技(www.yootk.com) —— 新时代软件教育领导品牌</strong>
</div>
</div>
</div>
</div>
</body>
</html>
3、
package com.yootk.servlet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yootk.dbc.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@WebServlet("/form.action") // 省份的加载
public class FormServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String sql = "SELECT pid,title FROM province"; // 获取全部省份信息
JSONArray array = new JSONArray();
try {
PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
JSONObject province = new JSONObject();
province.put("pid", rs.getLong(1));
province.put("title", rs.getString(2));
array.add(province); // 添加JSONObject项
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseConnection.close();
}
req.setAttribute("provinces", array.toJSONString());// 属性范围
req.getRequestDispatcher("/form.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
4、
<%@ page pageEncoding="UTF-8" %>
<html>
<head>
<title>沐言科技:www.yootk.com</title>
<script type="text/javascript" src="js/json3.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="jquery/Message_zh_CN.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
window.onload = function() { // 动态事件绑定
loadProvinceData(); // 调用省份信息加载函数
}
function loadProvinceData() { // 加载省份数据信息
jsonData = JSON.stringify(${provinces});
provinceJsonObject = JSON.parse(jsonData); // 响应数据
for (x = 0; x < provinceJsonObject.length; x ++) {
optionElement = document.createElement("option"); // 创建元素
optionElement.setAttribute("value",provinceJsonObject[x].pid);
optionElement.appendChild(document.createTextNode(provinceJsonObject[x].title));
document.getElementById("province").appendChild(optionElement);
}
}
</script>
</head>
<body>
<div> </div>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<strong><img src="images/logo.png" style="height: 30px;"> 【AJAX + JSON】级联菜单开发实例</strong>
</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-1">省份:</div>
<div class="col-md-5">
<select name="province" id="province" class="form-control">
<option value="">============= 请选择快递配送省份 =============</option>
</select>
</div>
<div class="col-md-1">城市:</div>
<div class="col-md-5">
<select name="city" id="city" class="form-control">
<option value="">============= 请选择快递配送城市 =============</option>
</select>
</div>
</div>
</div>
<div class="panel-footer">
<div style="text-align:right;">
<strong>沐言科技(www.yootk.com) —— 新时代软件教育领导品牌</strong>
</div>
</div>
</div>
</div>
</body>
</html>
异步数据验证
1、
DROP DATABASE IF EXISTS yootk ;
CREATE DATABASE yootk CHARACTER SET UTF8 ;
USE yootk ;
CREATE TABLE member(
mid VARCHAR(50) ,
name VARCHAR(50) ,
password VARCHAR(50) ,
CONSTRAINT pk_mid PRIMARY KEY(mid)
) engine=MyISAM;
INSERT INTO member(mid, name, password) VALUES ('muyan', 'yootk', 'java') ;
INSERT INTO member(mid, name, password) VALUES ('admin', 'lee', 'hello') ;
COMMIT;
2、
package com.yootk.servlet;
import com.yootk.dbc.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@WebServlet("/check.action")
public class CheckServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String mid = req.getParameter("mid"); // 接收用户名
String sql = "SELECT COUNT(*) FROM member WHERE mid=?"; // 查询SQL语句
boolean flag = false; // 不可以使用
try {
PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
pstmt.setString(1, mid); // 设置用户名
ResultSet rs = pstmt.executeQuery(); // 数据查询
if (rs.next()) {
long count = rs.getLong(1); // 获取个数
if (count == 0) {
flag = true; // 允许使用
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseConnection.close();
}
resp.getWriter().print(flag);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
3、
<html>
<head>
<title>沐言科技:www.yootk.com</title>
<base href="<%=basePath%>">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="jquery/Message_zh_CN.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<link href="bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
window.onload = function() { // 动态事件绑定
document.getElementById("mid").addEventListener("blur", function() {
mid = document.getElementById("mid"); // 表单的参数内容
if (mid) { // msg参数有内容
xmlHttpRequest = new XMLHttpRequest(); // 获取Ajax操作对象
if (xmlHttpRequest.withCredentials) { // 当前浏览器是否支持有Ajax操作
alert("对不起,您的浏览器不支持Aajx处理操作!");
} else { // 现在支持有Ajax的处理操作
xmlHttpRequest.open("post", "check.action"); // 建立通讯连接
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置头信息
xmlHttpRequest.onload = function (env) { // 接收响应数据
flag = xmlHttpRequest.responseText.trim(); // 响应数据
if (flag == "true") {
document.getElementById("midMsg").innerHTML = "<span class='success'>用户名可以使用!</span>"
} else {
document.getElementById("midMsg").innerHTML = "<span class='danger'>用户名重复!</span>"
}
}
xmlHttpRequest.send("mid=" + mid.value); // 发送请求参数
}
}
}, false);
}
</script>
</head>
<body>
<div> </div>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<strong><img src="images/logo.png" style="height: 30px;"> Ajax异步数据交互</strong>
</div>
<div class="panel-body">
<form action="" class="form-horizontal" id="myform" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group" id="fileDiv">
<label class="col-md-2 control-label" for="mid">用户名:</label>
<div class="col-md-5">
<input type="text" name="mid" id="mid" class="form-control input-sm" placeholder="请输入注册用户ID...">
</div>
<div class="col-md-4" id="midMsg">*</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<button type="button" class="btn btn-sm btn-primary" id="sendBut"><span class="glyphicon glyphicon-open"/> 发送</button>
<button type="reset" class="btn btn-sm btn-warning"><span class="glyphicon glyphicon-retweet"/> 重置</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="panel-footer">
<div style="text-align:right;">
<strong>沐言科技(www.yootk.com) —— 新时代软件教育领导品牌</strong>
</div>
</div>
</div>
</div>
</body>
</html>
验证码检测
1、
<%@ page pageEncoding="UTF-8"%> <%-- 设置页面编码 --%>
<%@ page contentType="image/jpeg"%> <%-- MIME显示风格为图片 --%>
<%@ page import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!Color getRandColor(int fc, int bc) { // 获取随机颜色
Random random = new Random();
if (fc > 255) { // 设置颜色边界
fc = 255;
}
if (bc > 255) { // 设置颜色边界
bc = 255;
}
int r = fc + random.nextInt(bc - fc); // 随机生成红色数值
int g = fc + random.nextInt(bc - fc); // 随机生成绿色数值
int b = fc + random.nextInt(bc - fc); // 随机生成蓝色数值
return new Color(r, g, b); // 随机返回颜色对象
}%>
<%
response.setHeader("Pragma", "No-cache"); // 【HTTP1.0】设置页面不缓存
response.setHeader("Cache-Control", "no-cache"); // 【HTTP1.1】设置页面不缓存
response.setDateHeader("Expires", 0); // 设置缓存失效时间
int width = 80; // 生成图片宽度
int height = 25; // 生成图片高度
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB); // 内存中创建图象
Graphics g = image.getGraphics(); // 获取图形上下文对象
Random random = new Random(); // 实例化随机数类
g.setColor(getRandColor(200, 250)); // 设定背景色
g.fillRect(0, 0, width, height); // 绘制矩形
g.setFont(new Font("宋体", Font.PLAIN, 18)); // 设定字体
g.setColor(getRandColor(160, 200)); // 获取新的颜色
for (int i = 0; i < 155; i++) { // 产生干扰线
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl); // 绘制长线
}
StringBuffer sRand = new StringBuffer(); // 保存生成的随机数
// 如果要使用中文,必须定义字库,可以使用数组进行定义,同时必须将中文转换为unicode编码
String[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
"L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "m", "n", "p", "s", "t", "u", "v", "w", "x", "y", "z",
"1", "2", "3", "4", "5", "6", "7", "8", "9" };
for (int i = 0; i < 4; i++) { // 生成4位随机数
String rand = str[random.nextInt(str.length)];// 获取随机数
sRand.append(rand); // 随机数保存
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110),
20 + random.nextInt(110))); // 将认证码显示到图象中
g.drawString(rand, 16 * i + 6, 19); // 图形绘制
}
session.setAttribute("rand", sRand.toString()); // 将认证码存入SESSION
g.dispose(); // 图象生效
ImageIO.write(image, "JPEG", response.getOutputStream());// 输出图象到页面
out.clear(); // 避免输出冲突
out = pageContext.pushBody(); // 避免输出冲突
%>
2、
package com.yootk.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/verify.action")
public class VerifyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String code = req.getParameter("code"); // 输入验证码
String rand = (String) req.getSession().getAttribute("rand"); // 获取数据生成信息
resp.getWriter().print(rand.equalsIgnoreCase(code)); // 验证码检测
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
3、
<html>
<head>
<title>沐言科技:www.yootk.com</title>
<base href="<%=basePath%>">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="jquery/Message_zh_CN.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<link href="bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
window.onload = function() { // 动态事件绑定
document.getElementById("code").addEventListener("blur", function() {
code = document.getElementById("code"); // 表单的参数内容
if (code.value) { // msg参数有内容
xmlHttpRequest = new XMLHttpRequest(); // 获取Ajax操作对象
if (xmlHttpRequest.withCredentials) { // 当前浏览器是否支持有Ajax操作
alert("对不起,您的浏览器不支持Aajx处理操作!");
} else { // 现在支持有Ajax的处理操作
xmlHttpRequest.open("post", "verify.action"); // 建立通讯连接
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置头信息
xmlHttpRequest.onload = function (env) { // 接收响应数据
flag = xmlHttpRequest.responseText.trim(); // 响应数据
if (flag == "true") {
document.getElementById("codeMsg").innerHTML = "<span class='success'>验证码输入正确!</span>"
} else {
code.value = ""; // 将原始已经输入的验证码的数据清空
document.getElementById("codeMsg").innerHTML = "<span class='danger'>验证码输入错误!!</span>"
document.getElementById("codeImg").src = "image.jsp?rd=" + Math.random();
}
}
xmlHttpRequest.send("code=" + code.value); // 发送请求参数
}
}
}, false);
}
</script>
</head>
<body>
<div> </div>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<strong><img src="images/logo.png" style="height: 30px;"> Ajax异步数据交互</strong>
</div>
<div class="panel-body">
<form action="" class="form-horizontal" id="myform" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group" id="fileDiv">
<label class="col-md-2 control-label" for="code">验证码:</label>
<div class="col-md-5">
<input type="text" name="code" id="code" class="form-control input-sm"
size="4" maxlength="4" placeholder="验证码">
</div>
<div class="col-md-2"><img src="image.jsp" id="codeImg"></div>
<div class="col-md-3" id="codeMsg">*</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<button type="button" class="btn btn-sm btn-primary" id="sendBut"><span class="glyphicon glyphicon-open"/> 发送</button>
<button type="reset" class="btn btn-sm btn-warning"><span class="glyphicon glyphicon-retweet"/> 重置</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="panel-footer">
<div style="text-align:right;">
<strong>沐言科技(www.yootk.com) —— 新时代软件教育领导品牌</strong>
</div>
</div>
</div>
</div>
</body>
</html>
XML 异步数据加载
1、
DROP DATABASE IF EXISTS yootk ;
CREATE DATABASE yootk CHARACTER SET UTF8 ;
USE yootk ;
CREATE TABLE dept (
deptno BIGINT AUTO_INCREMENT ,
dname VARCHAR(50) ,
loc VARCHAR(50) ,
CONSTRAINT pk_deptno PRIMARY KEY(deptno)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 开发部', '成都') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 教学部', '北京') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 财务部', '上海') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 市场部', '深圳') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 后勤部', '洛阳') ;
INSERT INTO dept(dname,loc) VALUES ('沐言科技 - 公关部', '广州') ;
COMMIT;
2、
package com.yootk.servlet;
import com.yootk.dbc.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@WebServlet("/dept.action")
public class DeptServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/xml;charset=UTF-8"); // XML数据响应
String sql = "SELECT deptno,dname,loc FROM dept"; // 查询SQL语句
Document document = DocumentHelper.createDocument(); // 创建Document实例
Element deptsElement = document.addElement("depts"); // 创建根元素
try {
PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(); // 数据查询
while (rs.next()) {
Element deptElement = deptsElement.addElement("dept"); // 获取dept信息
deptElement.addElement("deptno").setText(String.valueOf(rs.getLong(1)));
deptElement.addElement("dname").setText(rs.getString(2));
deptElement.addElement("loc").setText(rs.getString(3));
}
XMLWriter writer = new XMLWriter(resp.getOutputStream()); // XML直接输出
writer.write(document);
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseConnection.close();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
3、
<html>
<head>
<title>沐言科技:www.yootk.com</title>
<base href="<%=basePath%>">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="jquery/Message_zh_CN.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<link href="bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" />
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
window.onload = function() { // 动态事件绑定
document.getElementById("loadBut").addEventListener("click", function() {
xmlHttpRequest = new XMLHttpRequest(); // 获取Ajax操作对象
if (xmlHttpRequest.withCredentials) { // 当前浏览器是否支持有Ajax操作
alert("对不起,您的浏览器不支持Aajx处理操作!");
} else { // 现在支持有Ajax的处理操作
xmlHttpRequest.open("post", "dept.action"); // 建立通讯连接
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置头信息
xmlHttpRequest.onload = function (env) { // 接收响应数据
deptDOM = xmlHttpRequest.responseXML; // 获取XML返回的DOM对象
deptList = deptDOM.getElementsByTagName("dept");
for (x = 0; x < deptList.length; x ++) {
deptno = deptList[x].getElementsByTagName("deptno").item(0).firstChild.nodeValue;
dname = deptList[x].getElementsByTagName("dname").item(0).firstChild.nodeValue;
loc = deptList[x].getElementsByTagName("loc").item(0).firstChild.nodeValue;
trElement = document.createElement("tr");
trElement.setAttribute("id", "dept-" + deptno);
deptnoTdElement = document.createElement("td");
dnameTdElement = document.createElement("td");
locTdElement = document.createElement("td");
deptnoTdElement.appendChild(document.createTextNode(deptno));
dnameTdElement.appendChild(document.createTextNode(dname));
locTdElement.appendChild(document.createTextNode(loc));
trElement.appendChild(deptnoTdElement);
trElement.appendChild(dnameTdElement);
trElement.appendChild(locTdElement);
document.getElementById("deptBody").appendChild(trElement);
}
}
xmlHttpRequest.send(null); // 发送请求参数
}
}, false);
}
</script>
</head>
<body>
<div> </div>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
<strong><img src="images/logo.png" style="height: 30px;"> Ajax异步数据交互</strong>
<button class="btn btn-primary" id="loadBut">
<span class="glyphicon glyphicon-folder-open"> 加载部门信息</span>
</button>
</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr id="dept-title"><td>部门编号</td><td>部门名称</td><td>部门位置</td></tr>
</thead>
<tbody id="deptBody"></tbody>
</table>
</div>
<div class="panel-footer">
<div style="text-align:right;">
<strong>沐言科技(www.yootk.com) —— 新时代软件教育领导品牌</strong>
</div>
</div>
</div>
</div>
</body>
</html>
demo