search
HomeWeb Front-endJS TutorialExamples to explain the tradition of ajax user name verification and jquery's $.post method

This article mainly shares with you an example of the tradition of ajax implementation of user name verification and the $.post method of jquery. It has a good reference value and hopes to help everyone fully master ajax.

The first type: traditional ajax asynchronous request, the background code and effects are at the bottom

First we create a registration page in eclipse regist.jsp, create a form form. Note that since we are only implementing the effect of user name verification, the red departments below are the objects 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  class="captchaImage lazy"  src="/static/imghwm/default1.png"  data-src="${pageContext.request.contextPath}/checkImg.action"  id="checkImg"   onclick="change()" title="点击更换验证码" alt="Examples to explain the tradition of ajax user name verification and jquery's $.post method" ></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 achieve the above effects. 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(){
$(&#39;#username&#39;).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里面,
$(&#39;#span&#39;).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 the 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=&#39;green&#39;>用户名可以使用</font>");
}
return NONE;//此处返回空
}

The effect is as follows:

Related recommendations:


The specific implementation of JQuery user name verification_jquery

Perfect Implementation of ID card verification js regular method

JavaScript tutorial registration page form verification

The above is the detailed content of Examples to explain the tradition of ajax user name verification and jquery's $.post method. 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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function