function checkUserExists() {
var f = document.form1;
var username = f.username.value;
if (username == "") {
alert("用户名不能为空");
return false;
} else {
doAjax("CheckUserServlet?username=" + username);
}
}
创建XMLHttpRequest对象
var xmlhttp;
function doAjax(url) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmhttp = new XMLHttpRequest();
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType("text/xml");
}
} catch (e) { }
}
}
}
使用Ajax进行处理-checkname.jsp
1、创建XMLHttpRequest对象
2、设置在服务器完成后要运行的回调函数
3、设置请求信息
4、发送请求
function processRequest() {
var messdiv = document.getElementById(“mess”);
if (xmlhttp.readyState == 4)
if (xmlhttp.status == 200) {
//responseText表示请求完成后,返回的字符串信息
if (xmlhttp.responseText == "false")
messdiv.innerHTML = "用户名可以使用";
else
messdiv.innerHTML = "用户名已被使用";
} else {
alert("请求处理返回的数据有错误");
}
}
}
使用Ajax实现登录:下面是一个示例
function doAjax(){
createXMLHttpRequest();
var name = document.getElementById("uname").value;
var pwd = document.getElementById("upwd").value;
if(XMLHttp!=null){
var url ="LoginServlet?uname="+name+"&upwd="+pwd;
XMLHttp.open("POST",url,true);
XMLHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;");
XMLHttp.onreadystatechange=processRequest;
XMLHttp.send(null);
}else{
alert("不能创建XMLHttpRequest对象实例")
}
}
public class SearchSuggest extends HttpServlet {
public void doGet( …) {
…
String str = request.getParameter("search");
List strList=new ArrayList();
try{
if(str!=null&str.length()>0){
…
rs=stmt.executeQuery("select distinct(title) from
suggest where title like '"+str+"%' order by title");
while(rs.next())
strList.add(rs.getString("title")); StringBuffer sbu=new StringBuffer();
int size = strList.size();
for(int i=0;i<size;i++)
sbu.append((String)strList.get(i)+"-");
out.print(sbu.toString());
}
}catch(Exception e){ e.printStackTrace(); }
}
}
function processReuqest(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var sobj=document.getElementById("suggest");
sobj.innerHTML="";
var str= xmlhttp.responseText.split("-");
var suggest="";
if(str.length>0&&str[0].length>0){
for(i=0;i<str.length;i++){
suggest+="<div onmouseover='javascript:suggestOver(this);'";
suggest+=" onmouseout='javascript:suggestOut(this);'";
suggest+=" onclick='javascript:setSearch(this.innerHTML);'";
suggest+=" class='suggest_link'>"+str[i]+"</div>";
}
sobj.innerHTML=suggest;
document.getElementById("suggest").style.display="block";
}else{
document.getElementById("suggest").style.display="none";
}
}
}
}