Home Backend Development PHP Tutorial Ajax实时验证用户名/邮箱等是否已经存在的代码打包_php实例

Ajax实时验证用户名/邮箱等是否已经存在的代码打包_php实例

May 17, 2016 am 09:14 AM
username Mail

今天分享一个“利用Ajax技术来检测用户名是否存在”的例子。
利用Ajax技术来检测用户名是否存在的原理流程图:
Ajax实时验证用户名/邮箱等是否已经存在的代码打包_php实例

最终结果截图:

 


复制代码 代码如下:





Ajax检测用户名




用户名:





代码解释:
①实现该功能的核心代码在ajax.js,需要另外引进
②给form命名,因为后面我们需要利用JS来取得input框中的value
③给input框添加一个“onblur”事件,即当“焦点”失去时触发该事件(即流程图的“触发控件”)
用来放从服务器发送回来的数据(即“用户名已存在”等)
复制代码 代码如下:

mysql_connect("localhost",'root','');
mysql_select_db('test');
$sql="select * from ajax where name='$_GET[id]'";
$query=mysql_query($sql);
if(is_array(mysql_fetch_array($query))){
echo "用户名已存在";
}else{
echo "用户名可以使用";
}
?>

代码解释:
通过ajax的open方法,将用户输入”用户名“通过id传递给进来(即$_GET[id]),此时将对指定的数据库表中进行查询,检查是否有存在该“用户名”
ajax.js
复制代码 代码如下:

// JavaScript Document
var XHR; //定义一个全局对象
function createXHR(){ //首先我们得创建一个XMLHttpRequest对象
if(window.ActiveXObject){//IE的低版本系类
XHR=new ActiveXObject('Microsoft.XMLHTTP');//之前IE垄断了整个浏览器市场,没遵循W3C标准,所以就有了这句代码。。。但IE6之后开始有所改观
}else if(window.XMLHttpRequest){//非IE系列的浏览器,但包括IE7 IE8
XHR=new XMLHttpRequest();
}
}
function checkname(){
var username=document.myform.user.value;
createXHR();
XHR.open("GET","checkname.php?id="+username,true);//true:表示异步传输,而不等send()方法返回结果,这正是ajax的核心思想
XHR.onreadystatechange=byhongfei;//当状态改变时,调用byhongfei这个方法,方法的内容我们另外定义
XHR.send(null);
}
function byhongfei(){
if(XHR.readyState == 4){//关于Ajax引擎对象中的方法和属性,可以参考我的另一篇博文:http://www.cnblogs.com/hongfei/archive/2011/11/29/2265377.html
if(XHR.status == 200){
var textHTML=XHR.responseText;
document.getElementById('checkbox').innerHTML=textHTML;
}
}
}

代码解释:
①首先我们需要声明一个ajax引擎的对象:XHR(随便命名一个)
②因为微软的低版本IE和其他的浏览器创建ajax对象的方式不一样,现在IE和其他浏览器的市场份额几乎各占一半,所以我们得两方面都考虑到,IE-->ActiveXObject;其他-->XMLHttpRequest。我将她封装在一个函数中:createXHR
③我们在index.html中指定的当失去“焦点”时就会触发checkname()函数。那么我们如何将用户输入的“用户名”捕获呢?这里,利用js即可轻松捕获到document.myform.user.value(现在知道为何给form和input命名了吧,这一步对应流程图的“获得填写内容”),有兴趣的博友,可以试试在createXHR()的前一行敲行代码(alert(username)),将捕获到的用户名弹出试试看。
④Ajax引擎有几个方法和属性(可以参考我的另一篇博文:看图理解:普通交互方式和Ajax交互方式区别),使用之前我们得先调用函数craateXHR创建一个ajax对象
⑤有了ajax对象,有三个方法是必不可少的:open()、onreadystatechange、send()。
将请求发送到服务器,要使用open ()和send()方法
open()方法的第一个参数,指示采用GET或者POST方式进行传输。。。。。。
open()方法的第二个参数,指示要请求的URL地址(这里我们请求的是checkname.php文件),可以是绝对或相对地址
open()方法的第三个参数async指示是否采用异步请求,true为采用,这种情况下,通过ajax、js无需等待服务器响应,而是:①在等待服务器响应的同时执行其他脚本②当响应就绪后对响应进行处理。一般对一些小型的请求,async=false也是可以的,但此时就不要编写onreadystatechange 函数了
onreadystatechange事件:当ajax的属性readyState改变时,就触发此事件。在此事件中,当服务器响应已做好被处理的准备时(即readyState=4且status=200时),我们规定要让服务器做什么任务,这里我们规定将从数据库检索到的结果输出到id为”checkbox“的span标签中。
⑥通过checkname.php,查询数据库后,将得到查询结果(即服务器的响应,对应流程图中的”查询数据库“),此时数据还在ajax引擎中,如需获得该来自服务器的响应,我们需要使用XMLHttpRequest对象的responText或responseXML属性,并通过DOM属性innerHTML将从服务器响应回来的数据设置为id=”checkbox“的span标签的值
注:利用ajax监测邮箱是否存在一个道理,我们还可以利用ajax实时监测用户输入的密码强度,此时,需要用到可以把onblur事件改为onfocus事件。
原创 cnblogs 小飞

源码打包下载 /201112/yuanma/checkname_php.rar
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 get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

Master SQL LIMIT clause: Control the number of rows in a query Master SQL LIMIT clause: Control the number of rows in a query Apr 08, 2025 pm 07:00 PM

SQLLIMIT clause: Control the number of rows in query results. The LIMIT clause in SQL is used to limit the number of rows returned by the query. This is very useful when processing large data sets, paginated displays and test data, and can effectively improve query efficiency. Basic syntax of syntax: SELECTcolumn1,column2,...FROMtable_nameLIMITnumber_of_rows;number_of_rows: Specify the number of rows returned. Syntax with offset: SELECTcolumn1,column2,...FROMtable_nameLIMIToffset,number_of_rows;offset: Skip

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

Master SQL SELECT statements: A comprehensive guide Master SQL SELECT statements: A comprehensive guide Apr 08, 2025 pm 06:39 PM

SQLSELECT statement Detailed explanation SELECT statement is the most basic and commonly used command in SQL, used to extract data from database tables. The extracted data is presented as a result set. SELECT statement syntax SELECTcolumn1,column2,...FROMtable_nameWHEREconditionORDERBYcolumn_name[ASC|DESC]; SELECT statement component selection clause (SELECT): Specify the column to be retrieved. Use * to select all columns. For example: SELECTfirst_name,last_nameFROMemployees; Source clause (FR

Go language user registration: How to improve email sending efficiency? Go language user registration: How to improve email sending efficiency? Apr 02, 2025 am 09:06 AM

Optimization of the efficiency of email sending in the Go language registration function. In the process of learning Go language backend development, when implementing the user registration function, it is often necessary to send a urge...

How to design and create database tables after mysql installation How to design and create database tables after mysql installation Apr 08, 2025 am 11:39 AM

This article introduces the design and creation of MySQL database tables. 1. Understand key concepts such as relational databases, tables, fields, etc., and follow paradigm design; 2. Use SQL statements to create tables, such as CREATETABLE statements, and set constraints such as primary keys and unique keys; 3. Add indexes to improve query speed, and use foreign keys to maintain data integrity; 4. Avoid problems such as improper field type selection, unreasonable index design, and ignoring data integrity; 5. Select a suitable storage engine, optimize SQL statements and database parameters to improve performance. By learning these steps, you can efficiently create and manage MySQL database tables.

Is there a stored procedure in mysql Is there a stored procedure in mysql Apr 08, 2025 pm 03:45 PM

MySQL provides stored procedures, which are a precompiled SQL code block that encapsulates complex logic, improves code reusability and security. Its core functions include loops, conditional statements, cursors and transaction control. By calling stored procedures, users can complete database operations by simply inputting and outputting, without paying attention to internal implementations. However, it is necessary to pay attention to common problems such as syntax errors, permission problems and logic errors, and follow performance optimization and best practice principles.

See all articles