码迷,mamicode.com
首页 > Web开发 > 详细

ajax简单校验用户名是否存在

时间:2015-05-08 23:32:49      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:

1:注册表单
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>get方式请求数据,不要传参数</title> </head> <body> <input type="text" name="username" id="username" onblur="textAjax()"> <span id="mydiv" ></span> <input type="password" name="password"> <input type="button" value="测试是否可以注册" onclick="textAjax()"> <script type="text/javascript"> function textAjax() { //获取xmlHttpRequest对象(ajax引擎) var xmlhttprequest; if (window.XMLHttpRequest) { xmlhttprequest=new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari } else{ xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP"); //code for IE6, IE5 } //alert(xmlhttprequest);//说明获取对象成功 //与服务器建立连接,默认是true,异步,可以不写 xmlhttprequest.open("POST","${pageContext.request.contextPath}/sevletDemo2?time="+new Date().getTime(),true); //向服务器发送请求数据,没有为null,传递数据是post请求的 如username=jack&password=123 //post提交时候,如果不是表单要加请求头,,因为servlet要request.getParams(),如果是表单就不要默认ectype就是 //在send()前加context-type xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); var username=document.getElementById("username").value; xmlhttprequest.send("username="+username); xmlhttprequest.onreadystatechange=function(){ //alert(xmlhttprequest.readyState);4表示成功 //alert(xmlhttprequest.status);200表示成功 if(xmlhttprequest.readyState==4){ if(xmlhttprequest.status==200){ var mydiv=document.getElementById("mydiv"); mydiv.innerHTML=xmlhttprequest.responseText; } } } } </script> </body> </html>

2:请求的 servlet对客户端提交的数据进行校验

public class sevletDemo2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        response.setContentType("text/html;charset=UTF-8");
        String username=request.getParameter("username");
        PrintWriter writer=response.getWriter();
        System.out.println(username);
        if("jack".equals(username))
        {
            writer.write("用户名已存在");
        }
        else {
            
            writer.write("可以注册");
        }
    }

 

ajax简单校验用户名是否存在

标签:

原文地址:http://www.cnblogs.com/linhong/p/4489096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!