用于验证用户名是否可用的php ajax实现代码
时间:2011-03-09 来源:菊花一紧
//初始化、指定处理函数、发送请求的函数
//var poststr = "act=reply&bookid="+bookid+"&book_content="+ book_content;//type:post or get
function send_request(http_request,url,poststr) {
// 确定发送请求的方式和url以及是否同步执行下段代码
http_request.open("post", url, true);
http_request.setrequestheader("content-type","application/x-www-form-urlencoded");
http_request.send(poststr);
}
//创建对象 兼容多浏览xmlhttp创建方法
function create_obj(){
var http_request = false;
//开始初始化xmlhttprequest对象
if(window.xmlhttprequest) { //mozilla 浏览器
http_request = new xmlhttprequest();
if (http_request.overridemimetype) {//设置mime类别
http_request.overridemimetype("text/xml");
}
}
else if (window.activexobject) { // ie浏览器
try {
http_request = new activexobject("msxml2.xmlhttp");
} catch (e) {
try {
http_request = new activexobject("microsoft.xmlhttp");
} catch (e) {}
}
}
if (!http_request) { // 异常,创建对象实例失败
return false;
}
return http_request;
}
//这段代码是获取username值,发送到服务器端由php查询数据返回一个ture false验证用户名是否可用。
function getcheck(){var http_request = create_obj();
http_request.onreadystatechange = function(){
if (http_request.readystate == 4) {
if (http_request.status == 200) {
var http_result2 = http_request.responsetext;
if('该登录名可以使用'==http_result2){
cancel_popup_win('username',true);
username_check = true;
}else{
popup_win('username',http_result2);
username_check = false;
}
}
}
}
var username=document.getelementbyid('username').value;
var poststr = "act=check&userid="+ username;
send_request(http_request,"http://www.3ppt.com",poststr);
}
</script>
调用方法相对简单
<li>
<span class="dlm"><em>设置登录名:</em>
<input tabindex="1" class="text_2" name="username" id="username" value="" type="text" maxlength="16" autocomplete="off" onblur="getcheck();"/>登录名:4-16/怪字符/全数字/无内容/下划线/有全角/有空格/有大写/有汉字< /span>
</li>