AJAX在线基础(待续二)
例子一:用户检测,在输入用户名称的时候响应AJAX,检查是否存在用户,然后渲染页面
checkUser.jsp如下:页面的输入框值改变响应请求检验用户
<%@ page language="java" pageEncoding="utf-8"%>
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function checkUser() {
clear();
var user = document.getElementById("id").value;
xmlhttp = createXML();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4) {//readystate 为4即数据传输结束
if(xmlhttp.status == 200){
setResult(xmlhttp.responseText);
}
}
}
var url = "checkUser?username=" + user;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function clear() {
document.getElementById("result").innerHTML = "";
}
function createXML() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function setResult(result) {
var res = document.getElementById("result");
if(result == 'true') {
res.innerHTML = "<font color='black'>恭喜你该用户可以使用</font>";
}else {
res.innerHTML = "<font color='red'>对不起该用户已经存在</font>";
}
}
</script>
</head>
<body>
<input type="text" id="id" onchange="checkUser();"/><span id="result"></span>
</body>
</html>
checkUser.java代码如下:
package com.moom;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class checkUser extends HttpServlet {
private static List<String> users = new ArrayList<Strin