一、准备
1、tomcat解压文件 目录下找到 webapps目录建立TestAjax文件夹
2、按照 tomcat中建立可运行项目 建立个级文件夹
3、在RWQAjax文件夹内建立如下jsp文件
二、代码
ajaxTeset.jsp
[html]
<%@page language="java" contentType="text/html; charset=GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登录</title>
<script type="text/javascript">
var req;
function validate(){
var nameid = document.getElementById("userId");
var url="validate.jsp?id="+escape(nameid.value);
if(window.XMLHttpRequest){
req=new XMLHttpRequest();
}else if(window.ActiveXObject){
req=new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET",url,true);
req.onreadystatechange=callback;
req.send(null);
}
function callback(){
if(req.readyState==4){
if(req.status==200){
var msg = req.responseXML.getElementsByTagName("msg")[0];
setMsg(msg.childNodes[0].nodeValue);
}
}
}
function setMsg(msg){
mdiv = document.getElementById("usermsg");
if(msg=="invalid"){
mdiv.innerHTML="不存在"
}else{
mdiv.innerHTML="Valid"
}
}
</script>
</head>
<body>
<form action="" method="post">
<div
style="border-color: #0FF; width: 300px; height: 200px; margin: 0 auto; text-align: center; margin-top: 50px;">
<div
style="border-color: #0FF; width: 250px; height: 50px; margin: 0 auto; text-align: center; margin-top: 20px;">
<div>
<label>用户:</label><input type="text" name="user" id="userId" onblur="validate();"/>
</div>
<div id="usermsg">
</div>
<div style="margin-top: 10px; margin-bottom: 10px;">
密码:<input type="password" name="password" />
</div>
<div>
<input style="margin-right: 30px;" type="submit" value="登陆" />
</div>
</div>
<div></div>
</div>
</form>
</body>
</html>
validate.jsp
[html]
<% www.2cto.com
response.setContentType("text/xml");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires",0);
response.getWriter().write("<msg>invalid</msg>");
%>
三、运行效果
启动tomcat
运行效果如下
用户对应输入框任意输入数据,点输入框以外部分,会出现局部刷新的效果,显示一个提示信息