search
HomeBackend DevelopmentPHP TutorialDetailed example of using AJAX to complete asynchronous verification of user name

This article mainly introduces the relevant information on using AJAX to complete asynchronous verification of user names. Friends in need can refer to it. I hope it can help everyone.

Use AJAX to complete asynchronous verification of whether the user name exists:

1. Event triggering:

* onblur

2. Write AJAX code:

* Submit in item Action: pass username parameter

3. Write Action

* to receive username :Model driven reception.

4.* Write entity class

* User

* User.hbm.xml

* Configure into spring.

5. Write DAO

* Inherit HibernateDaoSupport

* Inject sessionFactory

## in the configuration #6. Write Service:

* Inject UserDao

* Transaction management:

Core code implementation:


function checkUsername(){ 
    // 获得文件框值: 
    var username = document.getElementById("username").value; 
    // 1.创建异步交互对象 
    var xhr = createXmlHttp(); 
    // 2.设置监听 
    xhr.onreadystatechange = function(){ 
      if(xhr.readyState == 4){ 
        if(xhr.status == 200){ 
          document.getElementById("span1").innerHTML = xhr.responseText; 
        } 
      } 
    } 
    // 3.打开连接 
    xhr.open("GET","${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username,true); 
    // 4.发送 
    xhr.send(null); 
  } 
  function createXmlHttp(){ 
      var xmlHttp; 
      try{ // Firefox, Opera 8.0+, Safari 
        xmlHttp=new XMLHttpRequest(); 
      } 
      catch (e){ 
        try{// Internet Explorer 
           xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
         } 
        catch (e){ 
         try{ 
           xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
         } 
         catch (e){} 
         } 
      } 
      return xmlHttp; 
     }


public String findByName() throws IOException { 
    // 调用Service进行查询: 
    User existUser = userService.findByUsername(user.getUsername()); 
    // 获得response对象,项页面输出: 
    HttpServletResponse response = ServletActionContext.getResponse(); 
    response.setContentType("text/html;charset=UTF-8"); 
    // 判断 
    if (existUser != null) { 
      // 查询到该用户:用户名已经存在 
      response.getWriter().println("<font color=&#39;red&#39;>用户名已经存在</font>"); 
    } else { 
      // 没查询到该用户:用户名可以使用 
      response.getWriter().println("<font color=&#39;green&#39;>用户名可以使用</font>"); 
    } 
    return NONE; 
  }


private UserDao userDao; 
  public void setUserDao(UserDao userDao) { 
    this.userDao = userDao; 
  } 
  // 按用户名查询用户的方法: 
  public User findByUsername(String username){ 
    return userDao.findByUsername(username); 
  }


public User findByUsername(String username){ 
    String hql = "from User where username = ?"; 
    List<User> list = this.getHibernateTemplate().find(hql, username); 
    if(list != null && list.size() > 0){ 
      return list.get(0); 
    } 
    return null; 
  }


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:aop="http://www.springframework.org/schema/aop" 
  xmlns:tx="http://www.springframework.org/schema/tx" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop.xsd 
  http://www.springframework.org/schema/tx  
  http://www.springframework.org/schema/tx/spring-tx.xsd"> 
  <!-- 配置连接池: --> 
  <!-- 引入外部属性文件 --> 
  <context:property-placeholder location="classpath:jdbc.properties"/> 
  <!-- 配置C3P0连接池: --> 
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
    <property name="driverClass" value="${jdbc.driver}"/> 
    <property name="jdbcUrl" value="${jdbc.url}"/> 
    <property name="user" value="${jdbc.user}"/> 
    <property name="password" value="${jdbc.password}"/> 
  </bean> 
  <!-- Hibernate的相关信息 --> 
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 
    <!-- 注入连接池 --> 
    <property name="dataSource" ref="dataSource"/> 
    <!-- 配置Hibernate的其他的属性 --> 
    <property name="hibernateProperties"> 
      <props> 
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
        <prop key="hibernate.show_sql">true</prop> 
        <prop key="hibernate.format_sql">true</prop> 
        <prop key="hibernate.connection.autocommit">false</prop> 
        <prop key="hibernate.hbm2ddl.auto">update</prop> 
      </props> 
    </property> 
    <!-- 配置Hibernate的映射文件 --> 
    <property name="mappingResources"> 
      <list> 
        <value>cn/itcast/shop/user/vo/User.hbm.xml</value> 
      </list> 
    </property> 
  </bean> 
  <!-- 事务管理: --> 
  <!-- 事务管理器 --> 
  <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="sessionFactory"/> 
  </bean> 
  <!-- 开启注解事务 --> 
  <tx:annotation-driven transaction-manager="transactionManager"/> 
  <!-- Action的配置 ===========================--> 
  <!-- 首页访问的Action --> 
  <bean id="indexAction" class="cn.itcast.shop.index.action.IndexAction" scope="prototype"> 
  </bean> 
  <!-- 配置验证码Action --> 
  <bean id="checkImgAction" class="cn.itcast.shop.user.action.CheckImgAction" scope="prototype"> 
  </bean> 
  <!-- 用户模块的Action --> 
  <bean id="userAction" class="cn.itcast.shop.user.action.UserAction" scope="prototype"> 
    <!-- 注入Service --> 
    <property name="userService" ref="userService"/> 
  </bean> 
  <!-- Service的配置 ===========================--> 
  <bean id="userService" class="cn.itcast.shop.user.service.UserService"> 
    <property name="userDao" ref="userDao"/> 
  </bean> 
  <!-- Dao的配置 ===========================--> 
  <bean id="userDao" class="cn.itcast.shop.user.dao.UserDao"> 
    <property name="sessionFactory" ref="sessionFactory"/> 
  </bean> 
</beans> 
[html] view plain copy 在CODE上查看代码片派生到我的代码片
<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE struts PUBLIC 
  "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 
  "http://struts.apache.org/dtds/struts-2.3.dtd"> 
<struts> 
  <constant name="struts.devMode" value="false" /> 
  <constant name="struts.enable.DynamicMethodInvocation" value="true"/> 
  <package name="shop" extends="struts-default" namespace="/"> 
    <global-results> 
      <result name="msg">/WEB-INF/jsp/msg.jsp</result> 
    </global-results> 
    <!-- 配置首页访问的Action --> 
    <action name="index" class="indexAction"> 
      <result name="index">/WEB-INF/jsp/index.jsp</result> 
    </action> 
    <!-- 配置用户模块的Action --> 
    <action name="user_*" class="userAction" method="{1}"> 
      <result name="registPage">/WEB-INF/jsp/regist.jsp</result> 
      <result name="input">/WEB-INF/jsp/regist.jsp</result> 
      <result name="loginPage">/WEB-INF/jsp/login.jsp</result> 
      <result name="login">/WEB-INF/jsp/login.jsp</result> 
      <result name="loginSuccess" type="redirectAction">index</result> 
      <result name="quit" type="redirectAction">index</result> 
      <result name="checkcodeFail">/WEB-INF/jsp/regist.jsp</result> 
    </action> 
    <!-- 验证码Action --> 
    <action name="checkImg" class="checkImgAction"></action> 
  </package> 
</struts>

Related recommendations;


Javascript rewrites the asynchronous verification form into a synchronous form_javascript skills

Detailed explanation of the traditional method of javascript to implement asynchronous verification_javascript skills

Examples explain the tradition of ajax implementation of user name verification and the $.post method of jquery

The above is the detailed content of Detailed example of using AJAX to complete asynchronous verification of user name. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

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.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

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.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.