Home Web Front-end JS Tutorial AJAX detect entered username without refreshing

AJAX detect entered username without refreshing

Mar 31, 2018 pm 03:09 PM
ajax case enter

This time I will bring you AJAX to detect the entered user name without refreshing. What are the precautions for AJAX to detect the entered user name without refreshing? The following is a practical case. Let’s take a look. 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="+$('username').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)
      //$('result').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+")");
      //$('result').value=mes_obj.res;
      //③+、json格式扩展
      var mes=myXmlHttpRequest.responseText;
      var mes_obj=eval("("+mes+")");
      $('result').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>
Copy after login

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.='{"res":"不可用","id":"123","age":"5"}';
// }else{
//  $info.='{"res":"可用","id":"3","age":"1"}';
// }
// echo $info;
 //③+
 $info="";
 if($username=="abc"){
  //这里的$info返回的是一个字串
  $info.='[{"res":"不可用","id":"123","age":"5"},{"res":"abc不可用","id":"3","age":"0"}]';
 }else{
  $info.='[{"res":"可用","id":"1","age":"15"},{"res":"可用","id":"83","age":"9"}]';
 }
 echo $info;
?>
Copy after login

Rendering:

# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to implement AJAX paging effect

Ajax to achieve infinite loading of lists and secondary drop-down menu options (attached Code)


How to use ajax to operate the form using JavaScript

The above is the detailed content of AJAX detect entered username without refreshing. 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)

Windows input encounters hang or high memory usage [Fix] Windows input encounters hang or high memory usage [Fix] Feb 19, 2024 pm 10:48 PM

The Windows input experience is a key system service responsible for processing user input from various human interface devices. It starts automatically at system startup and runs in the background. However, sometimes this service may automatically hang or occupy too much memory, resulting in reduced system performance. Therefore, it is crucial to monitor and manage this process in a timely manner to ensure system efficiency and stability. In this article, we will share how to fix issues where the Windows input experience hangs or causes high memory usage. The Windows Input Experience Service does not have a user interface, but it is closely related to handling basic system tasks and functions related to input devices. Its role is to help the Windows system understand every input entered by the user.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles