引用此文,请注意这页链接!
(一)在Eclipse中新建一个Java工程
工程名:ajax
然后在WebRoot下新建两个Jsp,一个为validate.jsp,它的作用是进行输入,提交;另一个为date.jsp它就是对输入值进行验证。
(二) validate.jsp 代码
<%@ page contentType="text/html; charset=GBK"%>
<html>
<head>
<title>数据验证</title>
<script type="text/javascript" >
<!---
/*
这个 button中的onClick()函数
作用:(1)进行输入框中的空值判定
(2)当不为空时,去调用可执行异步操作的函数
*/
function userCheck()
{
//下面取元素并没有用id这样的属性来取对应的值
var f=document.form1; //取出 form1所对应的元素
var username=f.username.value; //取出 from1下面username的值
alert('此元素的类型:'+f.username.type+' '+"/r/n此元素的名称:"+f.username.name);
if(username=="")
{
//window.alert("用户不能为空!"); 这两种都可以
alert("用户不能为空!");
f.username.focus(); //获得焦点
return false;
}else
{
//如果填写的不为空值的操作
send_request("date.jsp?username="+username);
}
}
var http_request=false;
//进行ajax的处理函数
function send_request(url)
{
//获取要调用的URL,传入函数
http_request=false;
if(window.XMLHttpRequest)
{
//Mozilla浏览器 或是非IE浏览器
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType)
{
http_request.overrideMimeType("text/html");
}
}else if(window.ActiveXObject)
{
//IE浏览器
try {
http_request=new ActiveXObject("Msxml2.XMLHTTP"); //Internet Explorer 中安装的 JavaScript 技术版本不同,MSXML 实际上有两种不同的版本,
}catch(e)
{
try
{
http_request=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
//当不能创建 XMLHttpRequest时
if(!http_request)
{
window.alert("不能创建XMLHttpRequest对象实例");
return false;
}
//processRequest虽然是一个函数,但在这不能加括号也不能给参数,更不能把下此函数的函数放在这句话的后面
http_request.onreadystatechange=processRequest;
//确定发送请求的方式和URL以及是否同步执行下段代码
//第一参数为传输的方式get post head 第二个参数为:要交互的URL;第三个参数:是否为异步传输
http_request.open("get",url,true);
http_request.send(null);
}
//处理返回信息的函数
function processRequest()
{
//代表从服务器中取的所有的值
if(http_request.readyState==4)
{
if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
//将输回的消息当字符串处理,还有responseXML(将输回来的消息当文档使用,可用DOM处理)
alert(http_request.responseText);
}else{
alert("您所请求的页面有异常。");
}
}
}
-->
</script>
</head>
<body>
<center>
<form name="form1" action="" method="post">
用户名:<input type="text" name="username" value="" > <br>
<input type="button" name="check" value="唯一性检查" onClick="userCheck()">
<input type="submit" name="submit" value="提交">
</form>
</center>
</body>
</html>
注意:括号要匹配,不然在<input type="button">这一行总会报缺少对象。
参考:XMLHttpRequest与浏览器之别 http://www.cnbruce.com/blog/showlog.asp?log_id=987&cat_id=34
(三)date.jsp 代码
<%@ page contentType="text/html; charset=GBK"%>
<%
String username = request.getParameter("username");
if ("liusong".equals(username.trim()))
{
out.println("用户名已经被注删,请更换一个用户名");
} else
{
out.println("用户尚未被使用,您可以继续");
}
%>
(三)运行
A::当什么出不输入时
B:输入不存的用户时
C:当输入的用户存在时