直接上代码: reg_ajax.html
<div class="jb51code">
<pre class="brush:xhtml;">
<!DOCTYPE html>
<script type="text/javascript">
/**
* 得到XMLHttpRequest对象
*/
function getajaxHttp() {
var xmlHttp;
try {
// Firefox,Opera 8.0+,Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的浏览器<a href="/tag/buzhichi/" target="_blank" class="keywords">不支持</a>AJAX!");
return false;
}
}
}
return xmlHttp;
}
/**
* 发送ajax请求
* url--请求到服务器的URL
* methodtype(post/get)
* con (true(异步)|false(同步))
* functionName(回调<a href="/tag/fangfa/" target="_blank" class="keywords">方法</a>名,不需要引号,这里只有成功的时候才<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>)
* (注意:这<a href="/tag/fangfa/" target="_blank" class="keywords">方法</a>有二个参数,一个就是xmlhttp,一个就是要处理的对象)
*/
function ajaxrequest(url,methodtype,con,functionName) {
//<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>XMLHTTPRequest对象
var xmlhttp = getajaxHttp();
//设置回调<a href="/tag/hanshu/" target="_blank" class="keywords">函数</a>(响应的时候<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>的<a href="/tag/hanshu/" target="_blank" class="keywords">函数</a>)
xmlhttp.onreadystatechange = function() {
//这个<a href="/tag/hanshu/" target="_blank" class="keywords">函数</a>中的<a href="/tag/daima/" target="_blank" class="keywords">代码</a>在什么时候被XMLHTTPRequest对象<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>?
//当服务器响应时,XMLHTTPRequest对象会<a href="/tag/zidong/" target="_blank" class="keywords">自动</a><a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>该回调<a href="/tag/fangfa/" target="_blank" class="keywords">方法</a>
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
functionName(xmlhttp.responseText);
}
}
};
//创建请求
xmlhttp.open(methodtype,url,con);
//发送请求
xmlhttp.send();
}
function checkUsername() {
var username=document.getElementById('username').value;
//<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>ajax请求Servlet
ajaxrequest("userServlet?username="+username,"POST",true,ckUsernameResponse);
}
function ckUsernameResponse(responseContents){
if (responseContents=='yes') {
document.getElementById('usernameMsg').innerHTML="<font color='red'><a href="/tag/yonghuming/" target="_blank" class="keywords">用户名</a>存在</font>";
document.getElementById('username').style="background-color: red";
}else{
document.getElementById('usernameMsg').innerHTML="";
document.getElementById('username').style="background-color: white";
}
}
<table>
<tr>
<td>用户名</td>
<td><input type="text" id="username" onblur="checkUsername()"/></td>
<td><div id="usernameMsg">