asynchronous(异步的)JavaScript and xml(用json来替代)
异步可以简单理解为发短信与打电话的区别,发短信的人不需要知道自己的短信有没有被阅读。
鼠标移出输入框触发onblur事件,JavaScript部分代码如下:
function checkUsernameByAjax(){
var xmlhttp = getXHP();
// 2)发送请求
xmlhttp.open("post","checkUsernameByAjax",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( "name="+document.getElementById("name").value);
// 3)回调函数
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("error_uname").innerHTML=xmlhttp.responseText;
}
}
// 1)获取AJAX引擎
function getXHP() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
}
servlet部分代码:
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
if("admin".equals(name))//这里写死用作演示
{
out.println("用户已注册");
} else {
out.println("用户可用");
}
out.flush();
out.close();