ajax uses $.post method to verify user name
This time I will bring to you how ajax uses $.post method to verify user name. Ajax uses $.post method to verify user name. What are the things to note?The following is a practical case. Get up and take a look.
The first type: traditional ajax asynchronous request, the background code and effects are at the bottom
First we create a ## in eclipse #Registration pageregist.jsp, create a form form. Note that since we only implement the effect of user name verification, the red department below is the object we need to study, so other departments can be ignored.
The content is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户注册</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/css/login.css" rel="external nofollow" > <script type="text/javascript"> //第三步:ajax异步请求用户名是否存在 function checkUsername(){ // 获得文本框值: var username = document.getElementById("username").value; // 1.创建异步交互对象 var xhr = createXmlHttp();//第二步中已经创建xmlHttpRequest,这里直接调用函数就可以了。 // 2.设置监听 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //把返回的数据放入到span中 document.getElementById("span").innerHTML = xhr.responseText;//responseText是后台返回的数据 } } } // 3.打开连接 xhr.open("GET","${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username,true); // 4.发送 xhr.send(null); } //第二部:创建xmlHttp对象 function createXmlHttp(){ var xmlHttpRequest; 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 xmlHttpRequest; } function change(){ var img1 = document.getElementById("checkImg"); img1.src="${pageContext.request.contextPath}/checkImg.action?"+new Date().getTime(); } </script> </head> <body> <form action="${pageContext.request.contextPath }/user_regist.action" method="post" onsubmit="return checkForm()";> <p class="regist"> <p class="regist_center"> <p class="regist_top"> <p class="left fl">会员注册</p> <p class="right fr"><a href="${pageContext.request.contextPath }/index.jsp" rel="external nofollow" target="_self">小米商城</a></p> <p class="clear"></p> <p class="xian center"></p> </p> <p class="regist_main center"> //第一步:首先,我们创建一个用户名input输入框,并添加一个onblur="checkUsername()"事件 <p class="username">用 户 名: <input class="shurukuang" type="text" id="username" name="username" onblur="checkUsername()"/><span id="span"></span></p> <p class="username">密 码: <input class="shurukuang" type="password" id="password" name="password"/></p> <p class="username">确认 密码: <input class="shurukuang" type="password" id="repassword" name="repassword" /></p> <p class="username">邮 箱 号: <input class="shurukuang" type="email" id="email" name="email" /></p> <p class="username">姓 名: <input class="shurukuang" type="text" id="name" name="name"/></p> <p class="username">手 机 号: <input class="shurukuang" type="text" id="phone" name="phone"/></p> <p class="username">地 址: <input class="shurukuang" type="text" id="addr" name="addr"/></p> <p class="username"> <p class="left fl">验 证 码: <input class="yanzhengma" type="text" id="checkcode" name="checkcode" maxlength="4"/></p> <p class="right fl"><img id="checkImg" class="captchaImage" src="${pageContext.request.contextPath}/checkImg.action" onclick="change()" title="点击更换验证码"></p> <p class="clear"></p> </p> </p> <p class="regist_submit"> <input class="submit" type="submit" name="submit" value="立即注册" > </p> </p> </p> </form> </body> </html>
The second way: use ajax in jQuery to achieve the above effect. First of all, the form and Action remain unchanged, we only need to change the script.
Step one: Introduce js file
Step 2:
//ajax异步请求用户名是否存在 $(function(){ $('#username').change(function(){//给username添加一个change事件 var val = $(this).val();//获取输入框的值 val = $.trim(val);//去空 if(val != ""){//判断值是否为空 var url = "${pageContext.request.contextPath}/user_findByName.action";//url还是那个URL var args ={"time":new Date().getTime(),"username":val};//这里和上面不同的是,这里用json方式实现传入的time和username参数 $.post(url,args,function(data){//发送post请求,后台返回的数据在data里面, $('#span').html(data);//把后台返回的数据放入span中 }); } }); })
Then let’s take a look at how the background data will be returned. Since I am implementing this using the ssh framework, for the sake of convenience, I only show how to return data in Action. Regarding the implementation of the service layer and dao layer in the ssh framework, please solve it yourself.
public class UserAction extends ActionSupport implements ModelDriven<User> { private static final long serialVersionUID = 1L; /** * 模型驱动 */ private User user = new User(); @Override public User getModel() { return user; } // 注入UserService private UserService userService; public void setUserService(UserService userService) { this.userService = userService; }
/** * AJAX进行异步校验用户名的执行方法 * * @throws IOException */ public String findByName() throws IOException { User existUser = userService.findByName(user.getUsername());//调用service层的方法返回数据库中查询出来的对象 // 获得response对象,向页面输出: HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8");//设置编码格式 // 判断返回的对象是否为空 if (existUser != null) { // 如果有,查询到该用户:用户名已经存在 response.getWriter().println("用户名已经存在"); } else { // 如果没有,用户名可以使用 response.getWriter().println("<font color='green'>用户名可以使用</font>"); } return NONE;//此处返回空 }
The effect is as follows:
##I believe you have read the case in this article After mastering the method, please pay attention to other related articles on the php Chinese website for more exciting content!
Recommended reading:
Detailed explanation of the steps to receive josn data using josnp in ajax
##How to use an elegant solution for front-end ajax requests accomplish
The above is the detailed content of ajax uses $.post method to verify 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

AI Hentai Generator
Generate AI Hentai for free.

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

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:

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

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.

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.

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.

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.
