ajax实例,检测用户与注册
检测用户名是否被占用:
在用户填写完用户名之后,ajax会异步向服务器发送请求,判断用户名是否存在
首先写好静态页面:
index.html
<!DOCTYPE html> <html lang="en"head> meta charset="UTF-8"title>index</style> *{ margin:0; padding; } body background-color #333 a text-decoration none .box width300px height270px80px auto #abcdef border-radius 5px15px 30px .box .title15px margin-bottom20px .box .title span font-size16px color#333 margin-right .box .title span.currentred .box div280px30px25px8px 10px #fff#666 position relative .box div span display inline-block padding-top4px padding-right6px .box div input bordernone outline margin-top5px .box div i absolute top14px right12px .box div i.ok backgroundurl(icon.png) no-repeat 0 -67px .box div i.nourl(icon.png) no-repeat -17px -67px .box div .info padding-left2px .button7px .button a block text-align center45px line-height #f20d0d#fff} bodydiv class="box"> p ="title"> span>登 录span ="current">注 册pdiv>+86input type="text" name="user" id placeholder="请输入注册手机号" autocomplete="off"i ="ok"></i="info">该手机号已注册="password"="pwd"="请设置密码"="no"="button"a href="javascript:void(0)"="btn" class="btn">注册ascript src="ajax.js"scripthtml>
效果图
然后是仿照jquery的$.ajax(),使用js封装了一个ajax方法(只是为了熟悉运行原理,实际项目可以直接用jquery封装好的)
ajax.js
//仿写jquery的ajax方法 var $={ ajax:function(options){ var xhr=null;XMLHttpRequest对象 var url=options.url,必填 type=options.type || "get",async=typeof(options.async)==="undefined"?true:options.async,data=options.data || null传递的参数 callback=options.success,1)">成功的回调 error=options.error;失败的回调 post传参的转换,将对象字面量形式转为字符串形式 data:{user:"13200000000",pwd:"123456"} xhr.send("user=13200000000&pwd=123456") if(data){ for(var i in data){ params+=i+"="+data[i]+"&"; } params=params.replace(/&$/,"");正则替换,以&结尾的将&转为空 } 根据type值修改传参 if(type==="get"){ url+="?"+params; } console.log(url); IE7+,其他浏览器 if(typeof XMLHttpRequest!="undefined"){ xhr=new XMLHttpRequest();返回xhr对象的实例 }else typeof ActiveXObject!="undefined"){ IE7及以下 所有可能出现的ActiveXObject版本 var arr=["Microsoft.XMLHTTP","MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP.2.0"]; 循环 var i=0,len=arr.length;i<len;i++){ try{ xhr=new ActiveXObject(arr[i]);任意一个版本支持,即可退出循环 break; }catch(e){ } } }else{ 都不支持 throw new Error("您的浏览器不支持XHR对象!"); } 响应状态变化的函数 xhr.onreadystatechange=(){ if(xhr.readyState===4if((xhr.status>=200&&xhr.status<300) || xhr.status===304){ callback&&callback(JSON.parse(xhr.responseText));如果存在回调则执行回调 }{ error&&error(); } } } 创建HTTP请求 xhr.open(type,url,async); 设置HTTP头 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 发送请求 xhr.send(params); },
jsonp:function(){
}
}
下面放出所有代码:
index.html
cursorpointer .button a.show="title"="off" data-check="reg"id="userIco"="info"="userInfo"="pwdIco"="pwdInfo"="btn show"="btn2">登录> var user=document.getElementById("user),userIcouserIcouserInfopwdpwdIcopwdInfobtnbtn2title).getElementsByTagName(span/^[1]\d{10}$//手机号格式的正则, pwdPattern^\w{5,10}$false默认不重复 绑定检测手机号事件 user.addEventListener(blur); 绑定检测密码事件 pwd.addEventListener(绑定注册事件 btn.addEventListener(click 切换登录绑定 title[].addEventListener( 切换注册绑定 1检测手机号方法 function checkUser(){ userValuser.value; if(!userPattern.test(userVal)){ userInfo.innerHTML手机号格式有误; userIco.classNameno; }else{ 格式正确时 userInfo.innerHTML""; 发起ajax请求 $.ajax({ url:http://localhost/reg/server/isUserRepeat.phpget传参 type:posttrue(data){ console.log(data); (data.code===){ userIco.classNameok; isRepeat; }else ){ userInfo.innerHTMLdata.msg; userIco.className手机号重复 }{ userInfo.innerHTML检测失败,请重试; } } }) } } 检测密码的方法 checkPwd(){ pwdValpwd.value; pwdPattern.test(pwdVal)){ pwdInfo.innerHTML密码格式有误; pwdIco.className pwdInfo.innerHTML; } } 注册的方法 regFn(){ user_valuser.value,pwd_valpwd.value; 再次检测用户名和密码是否合法 (userPattern.test(user_val) && pwdPattern.test(pwd_val) && isRepeat){ http://localhost/reg/server/register.php(data){ alert(注册成功~); 切换登录页面 showLogin(); user.value; pwd.value; },error:(){ pwdInfo.innerHTML注册失败,请重试!; } }) }不合法 } } 切换登录 showLogin(){ 切换到登录页面 title[].classNamecurrent; title[; btn2.classNamebtn show; btn.className; } 切换注册 showReg(){ ; } >
ajax.js上面已经贴过了
接下来是模拟服务器端的三个文件:
isUserRepeat.php
<?php header('Content-Type:application/json'); $isUsername = array_key_exists('username',$_REQUEST); $username = $isUsername ? $_REQUEST['username'] : ''; if(!$username){ $msg = printMsg('参数有误',2); echo json_encode($msgexit(); } function printMsg($msg,1)">$code){ return array('msg'=>); } 记录存储用户的文件路径 $fileStr = __DIR__.'/user.json' 读取现存的用户名和密码 $fileStream = fopen($fileStr,'r'); $fileContent = fread($fileStream,1)">filesize($fileStr)); $fileContent_array = $fileContent ? json_decode($fileContent,1)">true) : array(); fclose($fileStream); 判断用户名是否有重复的 $isrepeat = falseforeach($fileContent_array as $key=>$valif($val['username'] === ){ ; ; } } $isrepeat$msg = printMsg('用户名重复',0(); } $msg = printMsg('用户名可用',1); ?>
register.php
<? 获取前端传递的注册信息 字段为 username userpwd $isUserpwd = array_key_exists('userpwd',1)">; $userpwd = $isUserpwd ? $_REQUEST['userpwd'] : ''; $username || !$userpwdarray_push($fileContent_array,1)">array('username'=>$username,'userpwd'=>)); 将存储的用户名密码写入 fwrite($fileContent_array)); echo json_encode(printMsg('注册成功',1)">)); ?>
user.json
[{"username":"zhangsan","userpwd":"zhangsan"},{"username":"lisi","userpwd":"lisi"},{"username":"134","userpwd":"sdfsdf"},{"username":"135","userpwd":"dsff"},{"username":"136",{"username":"13521554677",{"username":"13521557890",{"username":"13521557891",{"username":"13810701234",{"username":"13810709999","userpwd":"shitou051031"},{"username":"13810709998","userpwd":"sdfsdfdsf"},{"username":"13412345678","userpwd":"shitou"},{"username":"13211111111","userpwd":"111111"},{"username":"13212222222",{"username":"13244444444","userpwd":"444444"}]
效果图
跳转到登录页面
补充:登录页面时不需要检测用户名是否重复,可以在手机号的输入框中添加 data-check 属性,如果是reg,则为注册效果;如果是login,则为登录效果
待完成……
还有jquery的跨域实现,jsonp如何实现:
把dataType属性设置为jsonp就可以
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。