


Detailed 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='red'>用户名已经存在</font>"); } else { // 没查询到该用户:用户名可以使用 response.getWriter().println("<font color='green'>用户名可以使用</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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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 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

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:

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.

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.

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.
