1.Ajax工作原理及其优缺点
1.什么是AJAX?
-
AJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML),是一种创建交互式网页应用的网页开发技术。它使用:
- 使用XHTML+CSS来标准化呈现;
- 使用XML和XSLT进行数据交换及相关操作;
- 使用XMLHttpRequest对象与Web服务器进行异步数据通信;
- 使用Javascript操作Document Object Model进行动态显示及交互;
- 使用JavaScript绑定和处理所有数据。
2.Ajax过程
- 创建XMLHttpRequest对象,也就是创建一个异步调用对象
- 创建一个新的HTTP请求,并指定其请求的方法、URL及验证信息
- 设置响应 HTTP 请求状态变化的函数
- 发送 HTTP 请求
- 获取异步调用返回的数据
- 使用 JavaScript 和 DOM 实现局部刷新
var xhr = null; // 创建异步对象
xhr = new XMLHttpRequest();
//xhr.open(get[post],url,true[false])
/*第一个参数提交方式:GET、POST最为常见。
* 第二个参数: 提交的路径
* 第三个参数:是以异步的方式还是同步的方式提交。
*/
xhr.open('get','http://localhost:4000/test',true); // true是异步,可省略
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //
xhr.onreadystatechange = function(){ // 若为同步,此代码不用写,直接在send后,用`xhr.responseText`即可。
if(xhr.readyState==4 && xhr.status==200){
/*readyState
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status
200 OK
404 Not Found*/
xhr.responseText;
xhr.responseXML.children[0].children;
JSON.parse(xhr.responseText);
}
}xhr.send(String); // 用于post传参,形式:"a=1&b=2",而get传参就在url后面用“?”拼接
3.Ajax的优缺点
优点: 可以使得页面不重载全部内容的情况下加载局部内容,降低数据传输量,避免用户
不断刷新或者跳转页面,提高用户体验
缺点:对搜索引擎不友好,要实现ajax下的前进后退功能成本较大;跨域问题限制
4.jQuery中的Ajax
jQuery代码:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$.ajax({url: ""}) 关于传参项,下面列举一些常用的:
-
url:String,一个用来包含发送请求的URL字符串
-
data:Object、String,发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后面。必须为 Key/Value 格式。
-
dataType :String
预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如XML MIME类型就被识别为XML。在1.4中,JSON就会生成一个JavaScript对象,而script则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:"xml": 返回 XML 文档,可用 jQuery 处理。 "html": 返回纯文本 HTML 信息;包含的script标签会在插入dom时执行。 "script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了"cache"参数。'''注意:'''在远程请求时(不在同一个域下),所有POST请求都将转为GET请求。(因为将使用DOM的script标签来加载) "json": 返回 JSON 数据 。 "jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。 "text": 返回纯文本字符串
-
success(data, textStatus, jqXHR) Function,Array
请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。
success:function (data, textStatus) { // data 可能是 xmlDoc, jsonObj, html, text, 等等... this; // 调用本次AJAX请求时传递的options参数 }
``
4.Ajax实例:验证码功能的实现
1.实验要求:
1.根据后台传过来的数据实时改变验证码
2.利用ajax实现异步刷新,页面不能跳转
2.使用技术
Spring SpringMVC Mybatis Mysql
-基本数据库知识Mysql
-Spring + SpringMVC + Mybatis
-框架MVC设计模式的应用
-前端页面(CSS+JS)
1.3开发环境
操作系统:Win10系统
开发语言:JavaEE JavaWeb
开发工具:Eclipse navicat
3.实验具体实现
- 登陆页面展示
- 具体代码
login.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<script src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
window.onload=function(){
var is_flag = "${is_flag}";
if(is_flag == "up_false"){
$("#span1").css('display','inline-block');
$("#span1").css('color','red');
}
if(is_flag == "cd_false"){
$("#span2").css('display','inline-block');
$("#span2").css('color','red');
}
createCode();
}
function createCode(){//ajax实现创建验证码
var divshow = $(".code");
$.ajax({
url : "create_code",//所跳转的servlet
type: "post",//提交方式
dataType : 'text',//服务器返回的数据类型
async : true,
success : function(data) {//data为后台传过来的数据
divshow.text("");//把之前的用空串代替,再添加上data
divshow.append(data);
},
error : function() {
}
});
}
</script>
</head>
<body>
<div id="head">
<img src="images/logo.png" />
<p class="text">软件学院学生信息管理系统</p>
</div>
<div id="body">
<div id="body-left">
<img src="images/login_bg.jpg">
</div>
<div id="body-right">
<h4 style="margin: 60px 0 5px 125px;"><strong style="color: #CC3300;">欢迎使用本系统</strong></h4>
<span id="span1" style="display: none">用户名或密码有误,请重新输入或<a>找回密码</a></span>
<span id="span2" style="display: none">验证码输入有误</span>
<form class="form-horizontal" style="margin: 25px auto; width: 400px;" action="login" method="post">
<div class="form-group" style="width: 600px; margin-bottom: 20px;">
<label for="inputEmail3" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input style="width: 200px;" type="text" class="form-control" name = "username" id="inputEmail3" placeholder="用户名">
</div>
</div>
<div class="form-group" style="width: 600px; margin-bottom: 20px;">
<label for="inputPassword3" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input style="width: 200px;" type="password" class="form-control" name = "password" placeholder="密码">
</div>
</div>
<div class="form-group" style="width: 600px; margin-bottom: 20px;">
<label for="inputPassword3" class="col-sm-2 control-label">验证码</label>
<div class="col-sm-10" >
<input style="width: 80px; float: left;" type="text" class="form-control" name="code" placeholder="验证码">
<div class="code" id="checkCode" onclick="createCode()"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox" style="margin-left: 30px;">
<label><input type="checkbox" > 记住密码<a href="" style="margin-left: 55px;">忘记密码?</a></label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10" style="width: 200px; margin-left: 100px;">
<button style="width: 200px;" type="submit" class="btn btn-danger">登陆</button>
</div>
</div>
<a href="regist.jsp" style="margin-left: 240px; margin-top: 30px;">立即注册</a>
</form>
</div>
</div>
</body>
</html>
控制器实现创建验证码
@RequestMapping("create_code")//create_codeServlet
public void create_code(HttpServletResponse res,HttpServletRequest req) throws IOException {
String result = null;//定义一个字符串用于返回前台数据
PrintWriter out = res.getWriter();
String string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//保存数字0-9 和 大小写字母
StringBuffer code = new StringBuffer();
for (int i = 0; i < 5; i++) {
Random random = new Random();
int index = random.nextInt(string.length());
char ch = string.charAt(index);
code.append(ch);//随机验证码的实现过程
}
req.getSession().setAttribute("Code",code.toString());
result=code.toString();//将验证码赋给要向前端返回的result
out.write(result);//将result返回给前端
}