search
HomeWeb Front-endJS Tutorialajax 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:

nbsp;html>


<meta>
<title>用户注册</title>
<link>
<script>
//第三步: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>


会员注册

小米商城

//第一步:首先,我们创建一个用户名input输入框,并添加一个onblur="checkUsername()"事件

用  户  名:  

密        码:  

确认 密码: 

邮  箱  号:  

姓        名:  

手  机  号:  

地        址:  

验  证  码:  

ajax uses $.post method to verify user name

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;
}</user>
/**
* 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>用户名可以使用</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!

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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.