1.首先从jquery官网下载个jquery.js,官网献上https://jquery.com/
放在咋们的web下面导入jquery链接
<script src="${pageContext.request.contextPath}/static/js/jquery.js"></script>
2.首先来一个ifram实现异步加载
<!DOCTYPE html>
<html lang="en">
<head x-frame-options SAMEORIGIN>
<meta charset="UTF-8">
<title>Ajax刷新页面初体验</title>
<script>
function go(){
var url1 = document.getElementById("url").value
document.getElementById("ifram").src=url1;
}
</script>
</head>
<body>
<div>
<span>请输入url地址</span>
<input type="text" id="url" value="https://www.baidu.com">
<input type="submit" value="提交" onclick="go()">
</div>
<div>
<iframe id="ifram" style="width: 100%;height: 500px" ></iframe>
</div>
</body>
</html>
3.简单网页的异步加载
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<script src="${pageContext.request.contextPath}/static/js/jquery.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/a1",
data:{"name":$("#username").val()},
success:function(data,status){
console.log(data) //status: 200 成功 300+ 重定向或转发 400+ 找不到资源或客户端错误 500+ 服务器错误
console.log(status) //status: 200 成功 300+ 重定向或转发 400+ 找不到资源或客户端错误 500+ 服务器错误
}
})
}
</script>
</head>
<body>
<span>请输入用户名</span>
<input type="text" onblur="a()" id="username">
</body>
</html>
4.下面来一个正式的表单提交,当失去焦点时,实现异步加载
登录界面 login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/js/jquery.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/a2",
data:{"name":$("#name").val()},
success:function(data){
if (data.toString()==="OK"){
$("#info1").css("color","green");
}else {
$("#info1").css("color", "red");
}
$("#info1").html(data)
}
})
}
function a2(){
$.post({
url:"${pageContext.request.contextPath}/a2",
data:{"password":$("#password").val()},
success:function(data){
if (data.toString()==="OK"){
$("#info2").css("color","green");
}else{
$("#info2").css("color","red");
}
$("#info2").html(data);
}
})
}
</script>
</head>
<body>
<p>
用户名 <input type="text" id="name" onblur="a1()">
<span id="info1"></span>
</p>
<p>
密码 <input type="password" id="password" onblur="a2()">
<span id="info2"></span>
</p>
</body>
</html>
5.ajax走的是a2的请求,后台来判断输的是否正确,本应从数据库中查找,这里只是个简单的测试
6.演示 失去焦点时自动弹出用户名输入错误的提示
7.当输入正确时自动弹出OK