Ajax典型应用——验证用户名是否可用

本文详细介绍了如何利用Ajax技术在客户端实时验证用户名的可用性,并通过Servlet接收并处理Ajax请求,在服务器端检查用户名是否已被使用,提供即时反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

步骤:

<!--
1.导入jQuery包 

2:获取 name="username"的节点,为该节点添加change()相应函数
3:获取username的属性值,去处前后空格,当不为空的时候,准备发送ajax请求
4:发送ajax请求,url为servlet,agrs为传递的json参数,该参数是像servlet中传递的,检验用户名是否可用
5:在服务端接受ajax传来的Json数据,并处理,结果返回一个html片段,将其添加到#message中。
 -->



<%@ page language="java" pageEncoding="UTF-8"%>
<html:html lang="true">
<head>
 <!--${pageContext.request.contextPath}获取该项目的绝对路径  -->
	<script type="text/javascript"
		src="${pageContext.request.contextPath}/scripts/jquery-1.7.2.js"></script>
	<script type="text/javascript">
      $(function(){
      $(":input[name='username']").change(function(){
         var val=$(this).val();  //获取username节点中的value属性值
         val=$.trim(val);        //取出前后空格
        if(val!=""){
                var url="${pageContext.request.contextPath}/valiateUserName";
                var agrs={"userNamesyq":val,"time":new Date()}; //准备传递的参数,注意该参数的类型设置为json格式的
                $.post(url,agrs,function(data){
                  $("#message").html(data);  //设置id="message"中的内容为data
                }); 
        }
      });
      }); 
 </script>
</head>
<body>
	<form action="" method="post">
		UserName:
		<input type="text" name="username" />
		<br>
		<br>
		<div id="message"></div>
		<br>
		<input type="submit" value="Submit" />

	</form>
</body>
</html:html>

servlet中检验用户名是否正确,并发送一个html片段给ajax

public class ValiateUserName extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<String> list=Arrays.asList("aaa","bbb","ccc");
		String userName=request.getParameter("userNamesyq"); //获取从ajax中传来的属性值,该数据是从ajax中的json中传来的
		System.out.println(userName+"**********");
		String result=null;
		if(list.contains(userName)){
			result="<font color='red'>该用户名已经被使用</font>";
		}else{
			result="<font color='green'>该用户名可以使用</font>";
		}
		response.setCharacterEncoding("UTF-8"); //解决中文乱码现象
		response.setContentType("text/html");  //设置传回数据的类型
		response.getWriter().print(result); //传回html数据
	}

}

实际上对用户名的检验要从数据库打交道,本程序只是讲解ajax检验用户名是否可用的原理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值