Home Web Front-end JS Tutorial Ajax no refresh verification registration information example

Ajax no refresh verification registration information example

Dec 30, 2017 pm 08:07 PM
ajax information register

这篇文章主要为大家详细介绍了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>
Copy after login


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;}
Copy after login


js代码


 <script src="../../../ajax.js"></script>
 <script>
  window.onload = function ()
  {
   //后台验证
   bgProcess();
   //提交注册信息,返回注册成功与否
   $(&#39;btn&#39;).onclick = function ()
   {
    var jsonData = {username:$(&#39;username&#39;).value,passw:$(&#39;passw&#39;).value,
     repassw:$(&#39;repassw&#39;).value,email:$(&#39;email&#39;).value};
    ajax(&#39;regProccess.php&#39;,jsonData,getInfo,&#39;json&#39;);
   };
   function getInfo(info)
   {
    var a = [&#39;username&#39;,&#39;passw&#39;,&#39;repassw&#39;,&#39;email&#39;];
    var b = [&#39;user&#39;,&#39;pass&#39;,&#39;rep&#39;,&#39;em&#39;];
    var flag = true;
    for(var i =0;i<info.length;i++)
    {
     if(info[i].state == &#39;false&#39;)
     {
      flag = false;
      displayInfo(info[i],b[i],a[i]); //显示错误信息
     }
    }
    if(flag) alert(&#39;恭喜你注册成功&#39;);
   }
  };
  //后台验证
  function bgProcess()
  {
   //验证用户名
   $(&#39;username&#39;).onblur = function ()
   {
    var jsonData = {username:this.value};
    ajax(&#39;regProccess.php&#39;,jsonData,getUser,&#39;json&#39;);
   };
   function getUser(msg)
   {
    displayInfo(msg[0],&#39;user&#39;,&#39;username&#39;);
   }
   //验证密码
   $(&#39;passw&#39;).onkeyup = $(&#39;passw&#39;).onblur= function ()
   {
    var jsonData = {passw:this.value};
    ajax(&#39;regProccess.php&#39;,jsonData,getPass,&#39;json&#39;);
   };
   function getPass(msg)
   {
    displayInfo(msg[1],&#39;pass&#39;,&#39;passw&#39;);
   }
   //确认密码
   $(&#39;repassw&#39;).onblur = function ()
   {
    var jsonData = {passw:$(&#39;passw&#39;).value,repassw:this.value};
    ajax(&#39;regProccess.php&#39;,jsonData,getRepass,&#39;json&#39;);
   };
   function getRepass(msg)
   {
    displayInfo(msg[2],&#39;rep&#39;,&#39;repassw&#39;);
   }
   //验证邮箱
   $(&#39;email&#39;).onblur= function ()
   {
    var jsonData = {email:this.value};
    ajax(&#39;regProccess.php&#39;,jsonData,getEmail,&#39;json&#39;);
   };
   function getEmail(msg)
   {
    displayInfo(msg[3],&#39;em&#39;,&#39;email&#39;);
   }
  }
  //显示信息
  function displayInfo(msg,id,name)
  {
   $(id).className = (msg.state == &#39;true&#39;)?&#39;ok&#39;:&#39;error&#39;;
   $(id).innerHTML = msg[name];
  }
  function $(id)
  {
   return document.getElementById(id);
  }
 </script>
Copy after login



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,&#39;用户名&#39;)) //验证该用户名是否被注册了
  $res[] = 1;
 else
  $res[] = 0;
 return $res;
}

/**
 * @function 验证密码是否非法和密码强度
 * @param $passw 密码
 * @return $res 密码强度
 */
function verifyPassw($passw)
{

 $reg1 = &#39;/^[0-9]{8,16}$/&#39;; //纯数字
 $reg2 = &#39;/^[a-zA-Z]{8,16}$/&#39;;//纯字母
 $reg3 = &#39;/^[a-zA-Z\+]{8,16}$/&#39;;//纯字母+
 $reg4 = &#39;/^[0-9a-zA-Z]{8,16}$/&#39;;//数字和字母组合
 $reg5 = &#39;/^[0-9a-zA-Z\+]{8,16}$/&#39;;//数字、&#39;+‘和字母组合
 $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 = &#39;/^([\w-*\.*])+@(\w-?)+(\.\w{2,})+$/&#39;;
 $res;
 if(empty($email))
  $res = -1;
 else if(verifyData($email,&#39;邮箱&#39;))
  $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(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;,&#39;user_passd&#39;);
 if(mysqli_connect_errno())
  die("连接数据库失败");
 //2.验证数据是否存在
 $sql = "select $query from login where $query = &#39;{$data}&#39;";
 $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(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;,&#39;user_passd&#39;);
 if(mysqli_connect_errno())
  die("连接数据库失败");
 //2.插入数据
 $sql = "insert into login values(&#39;{$data[0]}&#39;,&#39;{$data[1]}&#39;,&#39;{$data[2]}&#39;)";
 $res = $db->query($sql);
 //3.关闭数据库
 $db->close();
 return $res;
}
Copy after login


regProcess.php代码


<?php

header("Content-Type:text/html;charset=utf-8");
//禁用缓存,是为了数据一样的前提下还能正常提交,而不是缓存数据
header("Cache-Control:no-cache");
include(&#39;myFunc.php&#39;); //包含我的函数库
$username = isset($_POST[&#39;username&#39;])?$_POST[&#39;username&#39;]:&#39;&#39;; //获取用户名
$passw =isset($_POST[&#39;passw&#39;])?urlencode($_POST[&#39;passw&#39;]):&#39;&#39;;  //获取密码
$repassw = isset($_POST[&#39;repassw&#39;])?urlencode($_POST[&#39;repassw&#39;]):&#39;&#39;; //获取确认密码
$email = isset($_POST[&#39;email&#39;])?$_POST[&#39;email&#39;]:&#39;&#39;; //获取邮箱
$info=&#39;[&#39;;   //存放返回页面的数据
$isSucceed = 0; //判断注册是否成功,如果最后结果为4,则意味着全部正确,注册成功
//1.验证用户名是否非法
$res1 = verifyUser($username);
if($res1[1])
 $info.=&#39;{"username":"请输入用户名","state":"false"}&#39;;
else if($res1[0])
 $info.=&#39;{"username":"用户名非法","state":"false"}&#39;;
else if($res1[2])
 $info.=&#39;{"username":"用户名已存在","state":"false"}&#39;;
else
{
 $info.=&#39;{"username":"用户名可用","state":"true"}&#39;;
 ++$isSucceed;
}
$info.=&#39;,&#39;;
//2.验证密码是否非法和强度
$res2 = verifyPassw($passw);
if($res2 == -1)
 $info.=&#39;{"passw":"请输入密码","state":"false"}&#39;;
else if($res2 == 0)
 $info.=&#39;{"passw":"密码非法","state":"false"}&#39;;
else
{
 if($res2 == 1)
 $info.=&#39;{"passw":"密码强度较弱","state":"true"}&#39;;
 else if($res2 == 2)
 $info.=&#39;{"passw":"密码强度中等","state":"true"}&#39;;
 else if($res2 == 3)
 $info.=&#39;{"passw":"密码强度较强","state":"true"}&#39;;
 ++$isSucceed;
}

$info.=&#39;,&#39;;

//3.确认密码
if(empty($repassw))
 $info.=&#39;{"repassw":"请先输入密码","state":"false"}&#39;;
else if($passw == $repassw)
{
 $info.=&#39;{"repassw":"密码一致","state":"true"}&#39;;
 ++$isSucceed;
}
else
 $info.=&#39;{"repassw":"密码不一致","state":"false"}&#39;;
$info.=&#39;,&#39;;

//4.验证邮箱
$res3 = verifyEmail($email);
if($res3 == -1)
 $info.=&#39;{"email":"请输入邮箱","state":"false"}&#39;;
else if($res3 == 0)
 $info.=&#39;{"email":"邮箱非法","state":"false"}&#39;;
else if($res3 == 1)
 $info.=&#39;{"email":"此邮箱已被注册","state":"false"}&#39;;
else if($res3 == 2)
{
 $info.=&#39;{"email":"此邮箱可用","state":"true"}&#39;;
 ++$isSucceed;
}
//保存用户注册信息
if($isSucceed == 4)
 saveRegInfo(array($username,$passw,$email));
echo $info.=&#39;]&#39;;
Copy after login


这个例子虽然简单吧,但是还是可以让新手大概了解一下前端是怎么传数据给后端的,后端又是怎么返回数据给前端的.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

相关推荐:

实例详解ajax实现加载数据功能

实例详解ajax实现分页查询功能

实例详解Ajax实现漂亮、安全的登录界面

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to register multiple accounts on Xiaohongshu? Will I be discovered if I register multiple accounts? How to register multiple accounts on Xiaohongshu? Will I be discovered if I register multiple accounts? Mar 25, 2024 am 09:41 AM

As a platform integrating social networking and e-commerce, Xiaohongshu has attracted more and more users to join. Some users hope to register multiple accounts to better experience interacting with Xiaohongshu. So, how to register multiple accounts on Xiaohongshu? 1. How to register multiple accounts on Xiaohongshu? 1. Use different mobile phone numbers to register. Currently, Xiaohongshu mainly uses mobile phone numbers to register accounts. Users sometimes try to purchase multiple mobile phone number cards and use them to register multiple Xiaohongshu accounts. However, this approach has some limitations, because purchasing multiple mobile phone number cards is cumbersome and costly. 2. Use email to register. In addition to your mobile phone number, your email can also be used to register a Xiaohongshu account. Users can prepare multiple email addresses and then use these email addresses to register accounts. but

How to register a Manwa Comics account How to register a Manwa Comics account Feb 28, 2024 am 08:00 AM

On the Manwa Comics platform, there are rich comic resources waiting for everyone to explore. As long as you easily enter the official platform of Manwa Comics, you can enjoy all kinds of wonderful comic works. Everyone can easily find their favorite comics to read according to their own preferences. So how to register the official account of Manwa Comics? The editor of this website will bring you this detailed tutorial guide, hoping to help everyone in need. Manwa Comics-Official entrance: https://fuw11.cc/mw666 Manwa Comics app download address: https://www.siemens-home.cn/soft/74440.html Manwa Comics non-mainland area entrance: https: /

How to check what is registered with a mobile phone number 'Detailed explanation: APP query method for mobile phone number registration' How to check what is registered with a mobile phone number 'Detailed explanation: APP query method for mobile phone number registration' Feb 07, 2024 am 08:24 AM

I don’t know if you have such an experience. Your mobile phone often receives some inexplicable text messages, or registration information for some websites or other verification information. In fact, our mobile phone number may be bound to many unfamiliar websites, and we ourselves Even if you don’t know, what I will share with you today is to teach you how to unbind all unfamiliar websites with one click. Step 1: Open the number service platform. This technique is very practical. The steps are as follows: Open WeChat, click the plus icon in the search box, select Add Friend, and then enter the code number service platform to search. We can see that there is a number service platform. Of course, it belongs to a public institution and was launched by the National Institute of Information and Communications Technology. It can help everyone unbind mobile phone number information with one click. Step 2: Check whether the phone has been marked for me

How to register a Xiaohongshu account? What is required to register a Xiaohongshu account? How to register a Xiaohongshu account? What is required to register a Xiaohongshu account? Mar 22, 2024 am 10:16 AM

Xiaohongshu, a social platform integrating life, entertainment, shopping and sharing, has become an indispensable part of the daily life of many young people. So, how to register a Xiaohongshu account? 1. How to register a Xiaohongshu account? 1. Open the Xiaohongshu official website or download the Xiaohongshu APP. Click the &quot;Register&quot; button below and you can choose different registration methods. Currently, Xiaohongshu supports registration with mobile phone numbers, email addresses, and third-party accounts (such as WeChat, QQ, Weibo, etc.). 3. Fill in the relevant information. According to the selected registration method, fill in the corresponding mobile phone number, email address or third-party account information. 4. Set a password. Set a strong password to keep your account secure. 5. Complete the verification. Follow the prompts to complete mobile phone verification or email verification. 6. Perfect the individual

How to register 163 email How to register 163 email Feb 14, 2024 am 09:20 AM

Some users find that they do not have an account when they want to use 163 mailbox. So what should they do if they need to register an account at this time? Now let’s take a look at the 163 email registration method brought by the editor. 1. First, search the 163 Email official website in the browser and click [Register a new account] on the page; 2. Then select [Free Email] or [VIP Email]; 3. Finally, after selecting, fill in the information and click [Now Just register];

How to register a Xiaohongshu account? How to recover if its account is abnormal? How to register a Xiaohongshu account? How to recover if its account is abnormal? Mar 21, 2024 pm 04:57 PM

As one of the most popular lifestyle sharing platforms in the world, Xiaohongshu has attracted a large number of users. So, how to register a Xiaohongshu account? This article will introduce you to the Xiaohongshu account registration process in detail, and answer the question of how to recover Xiaohongshu account abnormalities. 1. How to register a Xiaohongshu account? 1. Download the Xiaohongshu APP: Search and download the Xiaohongshu APP in the mobile app store, and open it after the installation is complete. 2. Register an account: After opening the Xiaohongshu APP, click the &quot;Me&quot; button in the lower right corner of the homepage, and then select &quot;Register&quot;. 3. Fill in the registration information: Fill in the mobile phone number, set password, verification code and other registration information according to the prompts. 4. Complete personal information: After successful registration, follow the prompts to complete personal information, such as name, gender, birthday, etc. 5. Settings

How to register a qooapp account How to register a qooapp account Mar 19, 2024 pm 08:58 PM

qooapp is a software that can download many games, so how to register an account? Users need to click the &quot;Register&quot; button if they don't have a pass yet, and then choose a registration method. This account registration method introduction is enough to tell you how to operate it. The following is a detailed introduction, so take a look. How to register a qooapp account? Answer: Click to register, and then choose a registration method. Specific methods: 1. After entering the login interface, click below. Don’t have a pass yet? Apply now. 2. Then choose the login method you need. 3. You can use it directly after that. Official website registration: 1. Open the website https://apps.ppaooq.com/ and click on the upper right corner to register. 2. Select registration

How to check how long it has been since WeChat registration? How to check how long you have been registered on WeChat How to check how long it has been since WeChat registration? How to check how long you have been registered on WeChat Mar 13, 2024 am 08:52 AM

WeChat is a popular social software with rich functions and many users. If you want to check how long you have been registered on WeChat, although WeChat itself does not directly provide the function of checking the registration time, we can speculate through some indirect methods. However, these methods are not absolutely accurate as various factors may affect the accuracy of the results. If you have precise requirements for the registration time, it is recommended to contact WeChat customer service for consultation. How to check how long it has been since WeChat registration? The first way to see how long you have been registered on WeChat is by checking your QQ mailbox. If you use QQ to log in to WeChat, after successful registration, your QQ mailbox will receive a welcome email from WeChat. You can search for "WeChat" in your QQ mailbox to see if there is such an email, and then determine the registration time. The second way is by looking at

See all articles