ajax实现用户验证

<script type="text/javascript">
var xhr ;

//初始化 xhr 对象
// return value : 1 : IE , 2 , Mozila , 0 : create xhr error ;
function createXHR(){
//1,创建xhr 对象 .
if( window.ActiveXObject ){
xhr = new ActiveXObject( "Microsoft.XMLHTTP" ) ;
return 1 ;
}else if( window.XMLHttpRequest ){
xhr = new XMLHttpRequest();
return 2 ;
}else{
return 0 ;
}
}

用户名是否存在

//将用户填写的用户名发送到服务器端
function checkUserName(){
var ret = createXHR();
if( ret == 0 ){
alert( "create xhr error" ) ;
}else{
//在xhr中注册用于处理应答的函数(handleCheck)
xhr.onreadystatechange = handleCheck ;
/*
//使用Get方式向服务器发送请求 .
var url = makeQueryString( "/ajax/reg.jsp" );
xhr.open( "get" , url ) ;
xhr.send( null );
*/

//通过Post 形式向服务器发送数据 .
var url = "需要处理的action的地址" ;
xhr.open( "post" , url ) ;
xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" ) ;
xhr.send( makeQueryString( null ) ) ;
}
}

//在指定的URL上添加参数
function makeQueryString( url ){
var name = document.getElementById( "nameId" ).value ;
var queryString ;
if( url == null ){
return "name=" + name ;
}else{
return url + "?name=" + name ;
}
}

function handleCheck(){
//通信进程结束 .
//readyState : 1: 初始化阶段 2 :连接建立阶段 3 : 通信中阶段 4 : 通信结束
if( xhr.readyState == 4 ){
//status==200,表示服务器运行正常
if( xhr.status == 200 ){
processResult();
}else if(document.getElementById( "nameId" ).value==""){
document.getElementById( "nameId2" ).firstChild.nodeValue="用户名不能为空";
document.getElementById( "nameId2" ).color="red";


}
}
}

function processResult(){
//取得应答内容 ,把应答内容显示示在网页上
var span = document.getElementById( "msgId" ) ;
span.innerHTML = xhr.responseText ;
}
<script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值