学习AJAX参考了网上大量的实例,学得很艰难,代码可读性太差。本例就是一个入门的Hello World,类似本例的程序网上也许有,但是绝非抄袭。
本例很模仿用户注册,输入过程中动态检查错误实时显示,效果图如下:
![](https://i-blog.csdnimg.cn/blog_migrate/cd7a0c8dcad486c6dcd0d2cbc08de64e.png)
对着上面这个图,来写代码。
一、创建Java Web项目,并创建两个页面
a.html
<html>
<body>
<script language= "JavaScript">
var req = null;
function test() {
//初始化
var code = document.all.code.value;
var name = document.all.name.value;
req = new ActiveXObject( "Microsoft.XMLHTTP");
//设置属性,当后台处理完成后,回来调用myDeal方法。
req.onreadystatechange = myDeal;
//发出请求
req.open( "GET", "b.jsp?code=" + code + "&name=" + name, "false");
req.send( null);
}
function myDeal() {
if (req.readyState == 4) {
//接收服务端返回的数据
var ret = req.responseText;
//处理数据
document.all( "myDiv").innerHTML = ret;
}
}
</script>
用户注册:<br>
用户编号:<input type= "text" name= "code" οnblur= "test();">* <div id= "myDiv" name= "myDiv"></div><br>
用户名称:<input type= "text" name= "name"><br>
<input type= "button" value= "注册" οnclick= "test();">
</body>
</html>
<body>
<script language= "JavaScript">
var req = null;
function test() {
//初始化
var code = document.all.code.value;
var name = document.all.name.value;
req = new ActiveXObject( "Microsoft.XMLHTTP");
//设置属性,当后台处理完成后,回来调用myDeal方法。
req.onreadystatechange = myDeal;
//发出请求
req.open( "GET", "b.jsp?code=" + code + "&name=" + name, "false");
req.send( null);
}
function myDeal() {
if (req.readyState == 4) {
//接收服务端返回的数据
var ret = req.responseText;
//处理数据
document.all( "myDiv").innerHTML = ret;
}
}
</script>
用户注册:<br>
用户编号:<input type= "text" name= "code" οnblur= "test();">* <div id= "myDiv" name= "myDiv"></div><br>
用户名称:<input type= "text" name= "name"><br>
<input type= "button" value= "注册" οnclick= "test();">
</body>
</html>
创建处理表单数据的b.jsp
<%@ page contentType=
"text/html;charset=UTF-8" language=
"java" %>
<%
//接收参数
String code = request.getParameter( "code");
String name = request.getParameter( "name");
//控制台输出表单数据看看
System.out.println( "code=" + code + ",name=" + name);
//检查code的合法性
if (code == null || code.trim().length() == 0) {
out.println( "code can't be null or empty");
} else if (code != null && code.equals( "admin")) {
out.println( "code can't be admin");
} else {
out.println( "OK");
}
%>
<%
//接收参数
String code = request.getParameter( "code");
String name = request.getParameter( "name");
//控制台输出表单数据看看
System.out.println( "code=" + code + ",name=" + name);
//检查code的合法性
if (code == null || code.trim().length() == 0) {
out.println( "code can't be null or empty");
} else if (code != null && code.equals( "admin")) {
out.println( "code can't be admin");
} else {
out.println( "OK");
}
%>
二、部署运行
![](https://i-blog.csdnimg.cn/blog_migrate/92adad731a52dfa6281f10cf08064a23.png)
![](https://i-blog.csdnimg.cn/blog_migrate/87f086f17efb8290d03979674bb9fa00.png)