功能:
1.实现即时检查Email是否可用
2.实现无刷新的用户登录(不刷新整个页面,只刷新局部)
3.实现搜索自动提示
无刷新的好处:
1.只更新部分页面,有效利用带宽
2.提供连续的用户体验
3.提供类似C/S的交互效果,操作更方面
JavaScript对象XMLHttpRequest是整个Ajax技术的核心,它提供了异步发送请求的能力![](https://img-blog.csdnimg.cn/e2e5cfc75a9c4e6e9bceaaf27f3b0144.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAeOaIkC4=,size_20,color_FFFFFF,t_70,g_se,x_16)
Ajax例题演示(用户登录举例)
示意图:
以一个简单的表单,实现Ajax功能
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<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>
<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中
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();
}
}
在web.xml中配置
然后Ajax的登录就完成了