Ajax:只刷新局部页面的技术
Asynchronous JavaScript And Xml
JavaScript:AJAX技术的主要开发语言,实现更新局部的网页
XML:一般用于请求数据和响应数据的封装
异步:发送请求后不需等返回结果,由回调函数处理结果
index.jsp 使用ajax检查用户
<form action="" name="user" method="post">
用户名:<input id="user" name="name" onblur="check(this)">
<div id="mess" style="display:inline"></div>
<br/>
手机号:<input id="phone" name="phone">
</form>
<script>
var xmlhttp; //创建一个全局引擎对象
function check(v){
//1.创建引擎对象
xmlhttp=getRequest(); //getRequest方法为创建,自己写方法
//2.指定回调函数
xmlhttp.onreadystatechange=callback; //回调函数也是自己写
//3.设置请求方式
xmlhttp.open("post","AjaxServlet?name="+v.value);
//4.发送请求
xmlhttp.send(null);
}
function callback(){
//服务器端已经发送过来响应信息
if(xmlhttp.readyState==4){
//200代表服务器响应信息正常
if(xmlhttp.status==200){
if(xmlhttp.responseText=="1"){
document.getElementById("mess").innerHTML="用户名已存在!";
document.getElementById("mess").style.backgroundColor="red";
}else{
document.getElementById("mess").innerHTML="用户名可用!";
document.getElementById("mess").style.backgroundColor="red";
}
}
}
}
//专门创建XMLHttpRequest
function getRequest(){
if(window.XMLHttpRequest){
//在IE7及非IE浏览器中
xmlhttp = new XMLHttpRequest();
} else{
try {
//在较新的IE版本中
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//这是在IE7以前的版本中
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("对不起,您的浏览器不支持xmlHttpRequest对象");
}
}
}
return xmlhttp;
}
</script>
AjaxServlet.java doget()方法中的内容
request.setCharacterEncoding("UTF-8");
String user=request.getParameter("name");
if (user.equals("111")) {
response.getWriter().print("1");
}