Json与Ajax(注册实例)
程序员文章站
2022-05-18 09:13:01
需要在服务器上进行哈 jquery的ajax方法: // jquery请求 $.ajax({ url: "./server/slider.json", type: "post", dataType: "json", async: true, success: function(datas) { re ......
需要在服务器上进行哈
jquery的ajax方法:
// jquery请求 $.ajax({ url: "./server/slider.json", type: "post", datatype: "json", async: true, success: function(datas) { renderdata(datas.slider); } }) // jquery渲染数据 function renderdata(data) { var str = ""; $.each(data, function(index, obj) { str += '<a href="' + obj.linkurl + '"><img src="' + obj.picurl + '"></a>' }) $("#banner_jq").html(str); }
跨域请求,封装jsonp函数
function getjsonp(url, callback) { if (!url) { return; } var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; //定义一个数组以便产生随机函数名 var r1 = math.floor(math.random() * 10); var r2 = math.floor(math.random() * 10); var r3 = math.floor(math.random() * 10); var name = 'getjsonp' + a[r1] + a[r2] + a[r3]; var cbname = 'getjsonp.' + name; //作为jsonp函数的属性 if (url.indexof('?') === -1) { url += '?jsonp=' + cbname; } else { url += '&jsonp=' + cbname; } var script = document.createelement('script'); //定义被脚本执行的回调函数 getjsonp[name] = function(e) { try { callback && callback(e); } catch (e) { // } finally { //最后删除该函数与script元素 delete getjsonp[name]; script.parentnode.removechild(script); } } script.src = url; document.getelementsbytagname('head')[0].appendchild(script); } // 跨域调用 getjsonp('http://class.imooc.com/api/jsonp', function(response) { console.log(response); });
json和ajax登录功能
index.html
<!doctype html> <html lang="en"> <head> <title>register</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div class="register"> <p class="title" id="title"> <span>登 录</span> <span class="current">注 册</span> </p> <div class="form"> <div> <span>+86</span> <input type="text" name="user" id="user" placeholder="请输入注册手机号" autocomplete="off"/> <i id="user_icon"></i> <p class="info" id="user_info"></p> </div> <div> <input type="password" name="pwd" id="pwd" placeholder="请设置密码"> <i id="pwd_icon"></i> <p class="info" id="pwd_info"></p> </div> <p class="button"> <a href="javascript:void(0)" id="sigup-btn" class="btn show">注 册</a> <a href="javascript:void(0)" id="login-btn" class="btn">登 录</a> </p> </div> </div> <script type="text/javascript" src="js/ajax.js"></script> <script type="text/javascript"> var user = document.getelementbyid("user"), pwd = document.getelementbyid("pwd"), sigup = document.getelementbyid("sigup-btn"), login = document.getelementbyid("login-btn"), titles = document.getelementbyid("title").getelementsbytagname("span"); userinfo = document.getelementbyid("user_info"), usericon = document.getelementbyid("user_icon") pwdinfo = document.getelementbyid("pwd_info"), pwdicon = document.getelementbyid("pwd_icon"), userreg = /^1[3578]\d{9}$/, pwdreg = /^\w{5,12}$/, isrepeat = false; // 记录用户名是否被占用 // 检测用户 function checkuser(){ var userval = user.value; // 验证手机号是否有效 if(!userreg.test(userval)){ userinfo.innerhtml = '手机号码无效!'; usericon.classname = 'no'; }else{ userinfo.innerhtml = ''; usericon.classname = ''; // 发起请求 $.ajax({ url:'http://localhost/register/server/isuserrepeat.php', data:{username:userval}, success:function(data){ if(data.code == 1){ usericon.classname = 'ok'; isrepeat = false; }else if(data.code == 0){ usericon.classname = 'no'; isrepeat = true; userinfo.innerhtml = data.msg; }else{ userinfo.innerhtml = '检测失败,请重试...'; } } }) } } // 检测密码 function checkpwd(){ var pwdval = pwd.value; if(!pwdreg.test(pwdval)){ pwdinfo.innerhtml = '请输入5到12位的字母、数字及下划线'; pwdicon.classname = 'no'; }else{ pwdinfo.innerhtml = ''; pwdicon.classname = 'ok'; } } // 注册 function register(){ var user_val = user.value, pwd_val = pwd.value; // 如果手机号有效且没有被占用,同时密码合法,方可注册 if(userreg.test(user_val) && pwdreg.test(pwd_val) && !isrepeat){ // 发起请求,实现注册 $.ajax({ url:"http://localhost/register/server/register.php", method:"post", data:{username:user_val,userpwd:pwd_val}, success:function(data){ alert("注册成功,请登录!"); // 调用显示登录界面 showlogin(); // 清空文本框 user.value = ""; pwd.value = ""; }, error:function(){ pwdinfo.innerhtml = '注册失败,请重试!'; } }) } } // 显示登录 function showlogin(){ // 载入登录界面,登录高亮显示 titles[0].classname = "current"; titles[1].classname = ""; login.classname = "show"; sigup.classname = ""; } // 显示注册 function showsigup(){ // 载入注册界面,注册高亮显示 titles[1].classname = "current"; titles[0].classname = ""; login.classname = ""; sigup.classname = "show"; } // 绑定事件,检测用户的有效性及是否注册过 user.addeventlistener("blur",checkuser,false); // 绑定事件,检测密码的有效性 pwd.addeventlistener("blur",checkpwd,false); // 注册 sigup.addeventlistener("click",register,false); // 登录高亮 titles[0].addeventlistener("click",showlogin,false); // 注册高亮 titles[1].addeventlistener("click",showsigup,false); </script> </body> </html>
style.css
*{ margin:0; padding:0; } body{ background:#333; } .register{ width:300px; height:270px; margin:80px auto; padding:15px 30px; background:#eee; border-radius:5px; } .title{ height:35px; } .title span{ font-size:16px; font-weight:bold; color:#666; margin-right:30px; cursor:pointer; } .title span.current{ color:#f00; } .form div{ width:290px; height:30px; border-radius:8px; background:#fff; margin-bottom:40px; padding:8px 10px; position:relative; } .form div span{ display:inline-block; padding-top:8px; padding-right:3px; color:#666; } .form div input{ border:none; outline:none; font-size:17px; color:#666; background:none; } .form div i{ position:absolute; width:16px; height:16px; right:12px; top:14px; } .form div i.ok{ background:url(../img/icon.png) no-repeat 0 -67px; } .form div i.no{ background:url(../img/icon.png) no-repeat -17px -67px; } .form .info{ margin-top:22px; color:#f00; padding-left:2px; } .button{ padding-top:7px; } .button a{ display:none; width:100%; height:45px; line-height:45px; text-align:center; text-decoration:none; background:#f20d0d; color:#fff; border-radius:30px; font-size:16px; } .button a.show{ display:block; }
ajax.js
var $ = { ajax:function(options){ var xhr = null, // xmlhttprequest对象 url = options.url, // url地址 method = options.method || 'get', // 传输方式,默认为get async = typeof(options.async) === "undefined"?true:options.async, data = options.data || null, // 参数 params = '', callback = options.success, // ajax请求成功的回调函数 error = options.error; // 将data的对象字面量的形式转换为字符串形式 if(data){ for(var i in data){ params += i + '=' + data[i] + '&'; } params = params.replace(/&$/,""); } // 根据method的值改变url if(method === "get"){ url += '?'+params; } if(typeof xmlhttprequest != "undefined"){ xhr = new xmlhttprequest(); }else if(typeof activexobject != "undefined"){ // 将所有可能出现的activexobject版本放在一个数组中 var xhrarr = ['microsoft.xmlhttp','msxml2.xmlhttp.6.0','msxml2.xmlhttp.5.0','msxml2.xmlhttp.4.0','msxml2.xmlhttp.3.0','msxml2.xmlhttp.2.0']; // 遍历创建xmlhttprequest对象 var len = xhrarr.length; for(var i = 0;i<len;i++){ try{ // 创建xmlhttprequest对象 xhr = new activexobject(xhrarr[i]); break; } catch(ex){ } } }else{ throw new error('no xhr object availabel.'); } xhr.onreadystatechange = function(){ if(xhr.readystate === 4){ if((xhr.status >=200 && xhr.status <300) || xhr.status === 304){ callback && callback(json.parse(xhr.responsetext)) }else{ error && error(); } } } // 创建发送请求 xhr.open(method,url,async); xhr.setrequestheader("content-type","application/x-www-form-urlencoded"); xhr.send(params); }, jsonp:function(){ // 跨域 } }
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($msg); exit(); } function printmsg($msg,$code){ return array('msg'=>$msg,'code'=>$code); } // 记录存储用户的文件路径 $filestr = __dir__.'/user.json'; // 读取现存的用户名和密码 $filestream = fopen($filestr,'r'); $filecontent = fread($filestream,filesize($filestr)); $filecontent_array = $filecontent ? json_decode($filecontent,true) : array(); fclose($filestream); // 判断用户名是否有重复的 $isrepeat = false; foreach($filecontent_array as $key=>$val){ if($val['username'] === $username){ $isrepeat = true; break; } } if($isrepeat){ $msg = printmsg('用户名重复',0); echo json_encode($msg); exit(); } $msg = printmsg('用户名可用',1); echo json_encode($msg); ?>
register.php
<?php header('content-type:application/json'); // 获取前端传递的注册信息 字段为 username userpwd $isusername = array_key_exists('username',$_request); $isuserpwd = array_key_exists('userpwd',$_request); $username = $isusername ? $_request['username'] : ''; $userpwd = $isuserpwd ? $_request['userpwd'] : ''; function printmsg($msg,$code){ return array('msg'=>$msg,'code'=>$code); } if(!$username || !$userpwd){ $msg = printmsg('参数有误',0); echo json_encode($msg); exit(); } // 记录存储用户的文件路径 $filestr = __dir__.'/user.json'; // 读取现存的用户名和密码 $filestream = fopen($filestr,'r'); $filecontent = fread($filestream,filesize($filestr)); $filecontent_array = $filecontent ? json_decode($filecontent,true) : array(); fclose($filestream); // 判断用户名是否有重复的 $isrepeat = false; foreach($filecontent_array as $key=>$val){ if($val['username'] === $username){ $isrepeat = true; break; } } if($isrepeat){ $msg = printmsg('用户名重复',0); echo json_encode($msg); exit(); } array_push($filecontent_array,array('username'=>$username,'userpwd'=>$userpwd)); // 将存储的用户名密码写入 $filestream = fopen($filestr,'w'); fwrite($filestream,json_encode($filecontent_array)); fclose($filestream); 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","userpwd":"dsff"},{"username":"13521554677","userpwd":"sdfsdf"},{"username":"13521557890","userpwd":"sdfsdf"},{"username":"13521557891","userpwd":"sdfsdf"},{"username":"13810701234","userpwd":"sdfsdf"},{"username":"13810709999","userpwd":"shitou051031"},{"username":"13810709998","userpwd":"sdfsdfdsf"},{"username":"13412345678","userpwd":"shitou"}]
杂七杂八的知识点:
jquery 点击事件中触发的方式:
mousedown和mouseup事件鼠标左键点击和鼠标右键点击都是可以实现的;
click和dblclick事件只有鼠标左键点击才能实现
// jquery渲染数据
function renderdata(data) {
var str = "";
$.each(data, function(index, obj) {
str += '<a href="' + obj.linkurl + '"><img src="' + obj.picurl + '"></a>'
})
$("#banner_jq").html(str);
}
上一篇: Jquery基础(动画效果的轮播图特效)
下一篇: GitHub项目简介
推荐阅读
-
基于Django与ajax之间的json传输方法
-
javascript解析ajax返回的xml和json格式数据实例详解
-
thinkphp5 + ajax 使用formdata提交数据(包括文件上传) 后台返回json完整实例
-
PHP+Ajax检测用户名或邮件注册时是否已经存在实例教程
-
PHP数组对象与Json转换操作实例分析
-
Javascript 使用ajax与C#获取文件大小实例详解
-
jQuery与Ajax的应用(jQuery中的Ajax)实例讲解
-
js与jQuery实现的兼容多浏览器Ajax请求实例
-
angularJs中json数据转换与本地存储的实例
-
javascript和php使用ajax通信传递JSON的实例