var req;
function validate()
{
var idField=document.getElementById("userId");
//var url="ajaxUserRegister.jsp?userId="+escape(idField.value);//escape对中文有问题
var url="ajaxUserRegister.jsp?userId="+idField.value;
url=encodeURI(url);
url=encodeURI(url); //写一个不行。如果写一个就是????号。写2个,则输出 %df%a4这种.
//alert(url);
if(window.XMLHttpRequest){
req=new XMLHttpRequest();
}else if(window.ActiveXObject){
req=new ActiveXObject("Micrsoft.XMLHTTP");
}
req.open("GET",url,true);
req.onreadystatechange=callback;
req.send(null);
}
function callback() {
if(req.readyState == 4) {
if(req.status == 200) {
//alert(req.responseText);
var msg = req.responseXML.getElementsByTagName("msg")[0];
//alert(msg);
setMsg(msg.childNodes[0].nodeValue);
}
}
}
function setMsg(msg){
//alert(msg);
var mdiv=document.getElementById("usermsg");
if(msg=="no"){
mdiv.innerHTML="<font color='red'>username exists</font>"
}else if(msg=="yes"){
mdiv.innerHTML="<font color='green'>you can use the name</font>"
}else if(msg=="isNull"){
mdiv.innerHTML="<font color='red'>username can't be null</font>"
}
}
<td bgcolor="#D8F6F6" width="32%">
<html:text property="userId" size="30" maxlength="20" οnblur="validate()"/>
<span id="usermsg"></span>
</td>
ajaxUserRegister.jsp:
<%@ page language="java" import="com.wt.bean.User" %>
<%@ page import="com.wt.action.UserAction;"%>
<%
//response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml; charset=UTF-8");//xml,<msg>yes</msg>
response.setHeader("tCache-Control","no-cache");//HTTP1.1
response.setHeader("Pragma","no-cache");//HTTP1.0
response.setDateHeader("Expires",0);
//System.out.println("request.getParameter()===="+request.getParameter("userId"));
//check database
String userId=request.getParameter("userId");
if(userId==""||userId==null){
response.getWriter().write("<msg>isNull</msg>");
}else{
userId=java.net.URLDecoder.decode(userId,"UTF-8");//chinese <-->English
User user=UserAction.userService.getUser(userId);
if(user==null){
response.getWriter().write("<msg>yes</msg>");
}else{
response.getWriter().write("<msg>no</msg>");
}
}
%>