search
HomeWeb Front-endJS TutorialAJAX implements the function of detecting user names without refreshing

This article mainly introduces the AJAX non-refresh user name detection function in detail, which has certain reference value. Interested friends can refer to it

Let’s take a look at the schematic diagram first

register.php

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>ajax无刷新检测</title>
  <style type="text/css">
   body{margin:0;padding:0;}.content{width:800px;margin:0 auto;}ul,li{list-style: none;margin:0;padding:0;}
   tr{width:200px;}td{width:80px;padding:5px 0;}td input,textarea{border: 1px solid #79ABFE;} 
  </style>
 </head>
 <body>
  <p class="content">
   <script>
    myXmlHttpRequest.ContentType=("text/xml;charset=UTF-8");
    //创建ajax引擎(1号线)
    function getXmlHttpObject(){   
     var xmlHttpRequest;
     //不同浏览器获取对象xmlHttpRequest方法不一样
     if(window.ActiveXObject){
      xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
     }else{
      xmlHttpRequest=new XMLHttpRequest();
     }
     return xmlHttpRequest;
    }
    //验证用户名是否存在
    var myXmlHttpRequest="";//因为chuli也用到了,所以要定义为全局变量 
    //创建方法(2号线 http请求)
    function checkName(){
     //创建对象 
     myXmlHttpRequest=getXmlHttpObject();
     //判断是否创建ok
     if(myXmlHttpRequest){
      //通过myXmlHttpRequest对象发送请求到服务器的某个页面 
      var url="./registerPro1.php";
      //要发送的数据
      var data="username="+$(&#39;username&#39;).value;
      //打开请求
      myXmlHttpRequest.open("post",url,true);//ture表示使用异步机制
      //POST方法
      myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      //指定回调函数,chuli是函数名(registerPro里的数据返回给chuli函数)
      myXmlHttpRequest.onreadystatechange=chuli;
      //开始发送数据,如果是get请求则填入null即可,如果是post请求则填入实际的数据
      myXmlHttpRequest.send(data);
     }
    }
    //回调函数(4号线)
    function chuli(){
     //取出从registerPro.php页面返回的数据(4表示完成,200表示成功)
     if(myXmlHttpRequest.readyState==4){
      if(myXmlHttpRequest.status==200){
      //①、取出值,根据返回信息的格式定 text(html)
      //$(&#39;result&#39;).value=myXmlHttpRequest.responseText;
      //②、取出xml格式数据(解析)
      //获取mes节点、这里的mes返回的是节点列表(不知道有几个mes)
      //var mes=myXmlHttpRequest.responseXML.getElementsByTagName("mes");
      //取出mes节点值
      //mes[0]->表示取出第一个mes节点
      //mes[0].childNodes[0]->表示取出mes节点的第一个子节点
      //var mes_val=mes[0].childNodes[0].nodeValue;
      //$("result").value=mes_val; 
      //③、json格式
      //var mes=myXmlHttpRequest.responseText;
      //使用eval函数,将mes字串转为对象
      //var mes_obj=eval("("+mes+")");
      //$(&#39;result&#39;).value=mes_obj.res;
      //③+、json格式扩展
      var mes=myXmlHttpRequest.responseText;
      var mes_obj=eval("("+mes+")");
      $(&#39;result&#39;).value=mes_obj[0].res;
      }
     }
    }  
    //封装一个函数,通过id号获取对象
    function $(id){
     return document.getElementById(id);
    } 
   </script>
   <br/>
   <strong style="color:red">发表留言</strong>
   <form action="#" method="POST" name="frm">
   <table cellpadding="0" cellspacing="0" >
    <tr>
     <td >留言标题:</td>
     <td><input type="text" name="title" autocomplete="off"/></td>
    </tr>
    <tr>
     <td>网名:</td>
     <td>
      <input id="username" onkeyup="checkName();" type="text" name="username" autocomplete="off"/>
      <td><input id="result" type="text" style="width:110px;font-size: 12px;border-width:0;" ></td> 
     </td>
    </tr>
    <tr>
     <td>留言内容:</td>
     <td><textarea name="content" cols="26" rows="5" autocomplete="off"/ onclick="showNotice(this)"></textarea></td>
    </tr>
    <tr>
     <td></td>
     <td><input class="btn" type="submit" name="submit" value="提交"/></td>
    </tr>
   </table>
   </form>
  </p> 
 </body>
</html>

registerPro1.php

<?php
 //将数据(text格式,xml格式,json格式)返回到ajax引擎(3号线 http响应 )
 
 //header("Content-Type: text/xml; charset=utf-8"); //告诉浏览器,返回的是xml格式
 header("Content-Type: text/html; charset=utf-8"); //告诉浏览器,返回的是text/json格式
 $username = $_POST["username"];
 //①
// if($username=="abc"){
//  echo &#39;网名不可用&#39;;
// }else{
//  echo &#39;网名可用&#39;;
// }
 //②
// $info="";
// if($username=="abc"){
//  $info.="<res><mes>网名不可用</mes></res>";
// }else{
//  $info.="<res><mes>网名可用</mes></res>";
// }
// echo $info;
 //③
// $info="";
// if($username=="abc"){
//  //这里的$info返回的是一个字串
//  $info.=&#39;{"res":"不可用","id":"123","age":"5"}&#39;;
// }else{
//  $info.=&#39;{"res":"可用","id":"3","age":"1"}&#39;;
// }
// echo $info;
 //③+
 $info="";
 if($username=="abc"){
  //这里的$info返回的是一个字串
  $info.=&#39;[{"res":"不可用","id":"123","age":"5"},{"res":"abc不可用","id":"3","age":"0"}]&#39;;
 }else{
  $info.=&#39;[{"res":"可用","id":"1","age":"15"},{"res":"可用","id":"83","age":"9"}]&#39;;
 }
 echo $info;
?>

Rendering:

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

The problem of passing array parameters by calling webservice through ajax in jQuery (graphic tutorial)

Using ajax to pass arrays And a detailed explanation of the background receiving method

How to solve the problem of Ajax transmitting data with special characters

The above is the detailed content of AJAX implements the function of detecting user names without refreshing. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools