Ajax no refresh verification registration information example
这篇文章主要为大家详细介绍了ajax无刷新验证注册信息示例,具有一定的参考和学习ajax的价值,对ajax感兴趣的小伙伴们可以参考一下
ajax无刷新验证注册信息示例,其大概思路如下:
一.把注册的html页面做好(html+css)
1.不需要form表单,直接用p包着
2.需要四个标签来显示正确、错误的信息显示
3.不用submit提交按钮,直接用button
如图:
二.把ajax做成一个函数,通过传简单的参数可以与服务器进行数据交换.
1.这个ajax函数前面有一篇如何处理利用ajax处理返回数据的文章中详细说明了。
2.ajax函数需要三个参数,url,jsonData,getMsg。这里的url都是regProcess.php,jsonData则是要传到服务器验证的数据,getMsg就是要获取返回的数据的函数.
3.重复第2步骤就可以验证完四个信息
三.做一个处理注册信息的regProcess.php文件
1.这个就是要处理ajax传过来的数据,注意发送方式是POST所以接收方式也是POST
2.把数据都接收到以后,就是进行验证,判断了。最重要的还是能否把数据接收成功,千万不能接收错数据.
这里要注意一下,有一些特殊字符在传到服务器的的时候会显示不正确,例如‘+'会被显示成‘ '空格,详细的信息请自行搜索.所以服务器接收的时候如果会有特殊字符传过来,需要进行编码后才能正确使用.php使用urlencode这个函数来进行url编码.
四.把需要用到的功能编写成函数,放到另一个myFunc.php文件中,然后导入regProcess.php文件中直接使用.
1.验证用户名是否非法,是否已经注册
2.验证密码是否非法,强度有多大
3.验证密码是否输入一致
4.验证邮箱是否非法,是否已经注册
5.保存用户信息到数据库
然后在regProcess.php中,使用这些函数,直接处理返回的错误代码即可。
五.返回处理后的数据,这里我以字符串的json形式返回,然后JS再进行解析.
1.返回的数据要拼接成json的格式.
json格式: {name1:value1,name2:value2};
但是我们要返回的实际是是字符串,所以应该这样'{“name1”:”value1”,”name2”:”value2”}';
2.返回到前端后用JS的eval函数解析成一个json对象.
例如:var json = eval(‘(‘+oAjax.responseText+')');
3.把验证的信息显示在对应的input后面。
4.点击注册,一次性提交所有数据,如果没有错则保持注册用户信息,并提示注册成功.
注册成功效果如下图:
数据库也把刚注册的信息更新了
注册失败效果如下图:
下面是主要的代码:
html代码
<p id="reg"> <label>用户名:<input type="text" id="username" /></label><label></label><br /><br /> <label>密码:<input type="password" id="passw" /></label><br /><br /> <label>确认密码:<input type="password" id="repassw" /></label><br /><br /> <label>邮箱:<input type="text" id="email" /></label><br /><br /> <button id="btn">注册</button> <span id="user"></span> <span id="pass"></span> <span id="rep"></span> <span id="em"></span> </p>
css代码
#reg{width:400px;height: 300px;position: relative;margin:10px auto} #reg label{float:right;position: relative;margin-top: 10px;font-size: 28px;} #reg label input{width:250px;height: 40px;font-size: 24px;} #reg #btn{width:120px;height: 40px;position: absolute;right: 65px;margin-top: 80px;} #reg span{width:200px;position: absolute;right: -210px;font-size: 24px;} #reg #user{top:20px;} #reg #pass{top:75px;} #reg #rep{top:130px;} #reg #em{top:185px;} .error{color:red;} .ok{color:greenyellow;}
js代码
<script src="../../../ajax.js"></script> <script> window.onload = function () { //后台验证 bgProcess(); //提交注册信息,返回注册成功与否 $('btn').onclick = function () { var jsonData = {username:$('username').value,passw:$('passw').value, repassw:$('repassw').value,email:$('email').value}; ajax('regProccess.php',jsonData,getInfo,'json'); }; function getInfo(info) { var a = ['username','passw','repassw','email']; var b = ['user','pass','rep','em']; var flag = true; for(var i =0;i<info.length;i++) { if(info[i].state == 'false') { flag = false; displayInfo(info[i],b[i],a[i]); //显示错误信息 } } if(flag) alert('恭喜你注册成功'); } }; //后台验证 function bgProcess() { //验证用户名 $('username').onblur = function () { var jsonData = {username:this.value}; ajax('regProccess.php',jsonData,getUser,'json'); }; function getUser(msg) { displayInfo(msg[0],'user','username'); } //验证密码 $('passw').onkeyup = $('passw').onblur= function () { var jsonData = {passw:this.value}; ajax('regProccess.php',jsonData,getPass,'json'); }; function getPass(msg) { displayInfo(msg[1],'pass','passw'); } //确认密码 $('repassw').onblur = function () { var jsonData = {passw:$('passw').value,repassw:this.value}; ajax('regProccess.php',jsonData,getRepass,'json'); }; function getRepass(msg) { displayInfo(msg[2],'rep','repassw'); } //验证邮箱 $('email').onblur= function () { var jsonData = {email:this.value}; ajax('regProccess.php',jsonData,getEmail,'json'); }; function getEmail(msg) { displayInfo(msg[3],'em','email'); } } //显示信息 function displayInfo(msg,id,name) { $(id).className = (msg.state == 'true')?'ok':'error'; $(id).innerHTML = msg[name]; } function $(id) { return document.getElementById(id); } </script>
myFunc.php代码:
<?php /** * @function 验证用户名 * @param $username 用户名 * @return 返回一个$res数组,里面包含了错误代码,1:用户名非法,1:没有输入用户名,1:用户名存在 */ function verifyUser($username) { $res = array(); //匹配成功返回匹配次数,0表示没有匹配到,匹配字母、数字、下划线 if(preg_match("/^\\w{6,16}$/",$username) == 0) $res[] = 1; else $res[] = 0; if(empty($username)) $res[] = 1; else $res[] = 0; if(verifyData($username,'用户名')) //验证该用户名是否被注册了 $res[] = 1; else $res[] = 0; return $res; } /** * @function 验证密码是否非法和密码强度 * @param $passw 密码 * @return $res 密码强度 */ function verifyPassw($passw) { $reg1 = '/^[0-9]{8,16}$/'; //纯数字 $reg2 = '/^[a-zA-Z]{8,16}$/';//纯字母 $reg3 = '/^[a-zA-Z\+]{8,16}$/';//纯字母+ $reg4 = '/^[0-9a-zA-Z]{8,16}$/';//数字和字母组合 $reg5 = '/^[0-9a-zA-Z\+]{8,16}$/';//数字、'+‘和字母组合 $res; if(empty($passw)) $res = -1; else if(preg_match($reg1,$passw)) $res = 1; else if(preg_match($reg2,$passw)) $res = 1; else if(preg_match($reg3,$passw)) $res = 2; else if(preg_match($reg4,$passw)) $res = 2; else if(preg_match($reg5,$passw)) $res = 3; else $res = 0; //非法密码 return $res; } /** * @function 验证邮箱是否非法和是否已经被注册使用 * @param $email 邮箱 * @return $res 错误代码 */ function verifyEmail($email) { $reg = '/^([\w-*\.*])+@(\w-?)+(\.\w{2,})+$/'; $res; if(empty($email)) $res = -1; else if(verifyData($email,'邮箱')) $res = 1; else if(preg_match($reg,$email)) $res = 2; else $res = 0; //非法邮箱 return $res; } /** * @function 验证data是否已经存在 * @param $data * @param $query * @return data存在返回1,否则返回0 */ function verifyData($data,$query) { //1.连接数据库 @$db = new MySQLi('localhost','root','root','user_passd'); if(mysqli_connect_errno()) die("连接数据库失败"); //2.验证数据是否存在 $sql = "select $query from login where $query = '{$data}'"; $res = $db->query($sql); $row = $res->fetch_assoc(); //3.关闭数据库 $db->close(); return is_null($row)?0:1; } /** * @function 保存注册用户信息 * @param $data 要保存的数据,一个数组 * @return bool $res 返回true表示信息保存成功,false表示失败 */ function saveRegInfo($data) { //1.连接数据库 @$db = new MySQLi('localhost','root','root','user_passd'); if(mysqli_connect_errno()) die("连接数据库失败"); //2.插入数据 $sql = "insert into login values('{$data[0]}','{$data[1]}','{$data[2]}')"; $res = $db->query($sql); //3.关闭数据库 $db->close(); return $res; }
regProcess.php代码
<?php header("Content-Type:text/html;charset=utf-8"); //禁用缓存,是为了数据一样的前提下还能正常提交,而不是缓存数据 header("Cache-Control:no-cache"); include('myFunc.php'); //包含我的函数库 $username = isset($_POST['username'])?$_POST['username']:''; //获取用户名 $passw =isset($_POST['passw'])?urlencode($_POST['passw']):''; //获取密码 $repassw = isset($_POST['repassw'])?urlencode($_POST['repassw']):''; //获取确认密码 $email = isset($_POST['email'])?$_POST['email']:''; //获取邮箱 $info='['; //存放返回页面的数据 $isSucceed = 0; //判断注册是否成功,如果最后结果为4,则意味着全部正确,注册成功 //1.验证用户名是否非法 $res1 = verifyUser($username); if($res1[1]) $info.='{"username":"请输入用户名","state":"false"}'; else if($res1[0]) $info.='{"username":"用户名非法","state":"false"}'; else if($res1[2]) $info.='{"username":"用户名已存在","state":"false"}'; else { $info.='{"username":"用户名可用","state":"true"}'; ++$isSucceed; } $info.=','; //2.验证密码是否非法和强度 $res2 = verifyPassw($passw); if($res2 == -1) $info.='{"passw":"请输入密码","state":"false"}'; else if($res2 == 0) $info.='{"passw":"密码非法","state":"false"}'; else { if($res2 == 1) $info.='{"passw":"密码强度较弱","state":"true"}'; else if($res2 == 2) $info.='{"passw":"密码强度中等","state":"true"}'; else if($res2 == 3) $info.='{"passw":"密码强度较强","state":"true"}'; ++$isSucceed; } $info.=','; //3.确认密码 if(empty($repassw)) $info.='{"repassw":"请先输入密码","state":"false"}'; else if($passw == $repassw) { $info.='{"repassw":"密码一致","state":"true"}'; ++$isSucceed; } else $info.='{"repassw":"密码不一致","state":"false"}'; $info.=','; //4.验证邮箱 $res3 = verifyEmail($email); if($res3 == -1) $info.='{"email":"请输入邮箱","state":"false"}'; else if($res3 == 0) $info.='{"email":"邮箱非法","state":"false"}'; else if($res3 == 1) $info.='{"email":"此邮箱已被注册","state":"false"}'; else if($res3 == 2) { $info.='{"email":"此邮箱可用","state":"true"}'; ++$isSucceed; } //保存用户注册信息 if($isSucceed == 4) saveRegInfo(array($username,$passw,$email)); echo $info.=']';
这个例子虽然简单吧,但是还是可以让新手大概了解一下前端是怎么传数据给后端的,后端又是怎么返回数据给前端的.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
相关推荐:
The above is the detailed content of Ajax no refresh verification registration information example. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor