需要在服务器上进行哈

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:;
padding:;
} 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);

}

Json与Ajax(注册实例)的更多相关文章

  1. day 74 json 和 ajax 的实例

    一 json的定义: json(JavaScript object notation,js对象标记)是一种轻量级的数据交换格式,它基于ecmascript(w3c指定的js规范)的一个子集,采用完全独 ...

  2. Django JSON,AJAX

    JSON 概念 JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻量级的文本数据交换格式 JSON 独立于语言 * JSON 具 ...

  3. jQuery&nbsp;Ajax&nbsp;实例&nbsp;全解析

    jQuery Ajax 实例 全解析 jQuery确实是一个挺好的轻量级的JS框架,能帮助我们快速的开发JS应用,并在一定程度上改变了我们写JavaScript代码的习惯. 废话少说,直接进入正题,我 ...

  4. Json.Net系列教程 1.Json.Net介绍及实例

    原文 Json.Net系列教程 1.Json.Net介绍及实例 本系列教程假设读者已经对Json有一定的了解,关于Json在这里不多说.本系列教程希望能对读者开发涉及到Json的.Net项目有一定的帮 ...

  5. ajax常用实例代码总结新手向参考(一)

    http的交互方法有四种:get.post.put(增加数据).delete(删除数据) put和delete实现用的是get和post   get方式 页面不能被修改,只是获取查询信息.但是提交的数 ...

  6. Node.js_express_中间件 middleware_登录/注册实例源代码

    静态资源: 都写死了的资源,如 css,html 解析规则: 所有路由和中间件都在一个数组中,js 引擎会按照代码先后顺序添加路由和中间件 当请求发送到服务器时,服务器获取当前的请求信息(请求方式.请 ...

  7. thinkphp中ajax使用实例(thinkphp内置支持ajax)

    thinkphp中ajax使用实例(thinkphp内置支持ajax) 一.总结 1.thinkphp应该是内置支持ajax的,所以请求类型里面才会有是否是ajax // 是否为 Ajax 请求 if ...

  8. Django登录(含随机生成图片验证码)注册实例

    登录,生成随机图片验证码 一.登录 - 随机生成图片验证码 1.随机生成验证码 Python随机生成图片验证码,需要使用PIL模块,安装方式如下: pip3 install pillow 1)创建图片 ...

  9. Ajax注册验证用户名是否存在 ——引自百度经验

    Ajax注册验证用户名是否存在 http://jingyan.baidu.com/article/a948d6515fdf870a2dcd2e85.html

随机推荐

  1. 机器学习(ML)九之GRU、LSTM、深度神经网络、双向循环神经网络

    门控循环单元(GRU) 循环神经网络中的梯度计算方法.当时间步数较大或者时间步较小时,循环神经网络的梯度较容易出现衰减或爆炸.虽然裁剪梯度可以应对梯度爆炸,但无法解决梯度衰减的问题.通常由于这个原因, ...

  2. Codeforces_731_F

    http://codeforces.com/problemset/problem/731/F 其实是暴力枚举,但是有些小技巧,直接保存每个数的数量. 枚举每个起点时,然后依次加上起点大小的分段的数量的 ...

  3. uniapp单页面配置无导航栏

    { "path": "pages/login/login", "style": { "navigationStyle": ...

  4. Linux中查看日志文件的正确姿势,求你别tail走天下了!

    作为一个后端开发工程师,在Linux中查看查看文件内容是基本操作了.尤其是通常要分析日志文件排查问题,那么我们应该如何正确打开日志文件呢?对于笔者这种小菜鸡来说,第一反应就是 cat,tail,vi( ...

  5. Vue项目使用vant框架

    近期在开发h5端项目,用到vant框架,vant是一款基于Vue的移动UI组件,看了vant的官方文档(https://youzan.github.io/vant/#/zh-CN/)感觉不错,功能比较 ...

  6. Hapi+MySql项目实战配置插件-加载文件渲染母版(三)

    加载插件 一般在其它node框架下,我们安装好插件直接require('插件')就能正常使用了,但是在Hapi下我们必须要Server.register()方法,才能正常使用插件.举个例子: serv ...

  7. sparc v8 stack frame calling convention

    main.c ; int main() { int a, b; int sum; a = ; b = ; sum = add(a, b); ; } int add(int a, int b) { in ...

  8. Linux系统下常见的数据盘分区丢失的问题以及对应的处理方法

    在修复数据前,您必须先对分区丢失的数据盘创建快照,在快照创建完成后再尝试修复.如果在修复过程中出现问题,您可以通过快照回滚将数据盘还原到修复之前的状态. 前提条件 在修复数据前,您必须先对分区丢失的数 ...

  9. [RHEL8]关闭SELinux(同CentOS7)

    修改配置文件(永久修改) # vi /etc/selinux/config SELINUX=disabled # 关闭 SELINUX=enforcing # 开启 命令方式(临时修改重启失效) # ...

  10. C#基础知识学习(2)string类中的方法

    1.Compare 比较字符串 用来比较2个字符串的长度大小和值是否相同,相同则返回0,当x比y小返回-1,否则返回1,如果长度相同,且值不同,则返回1,代码如下 public static void ...