需求: 利用ajax实现 当输入用户名时,验证该用户名是否已经存在,如果存在,给出重新输入用户名,不存在,提示可以使用。简单起见,如果用户名不等于 'shizhan',则可以使用。
html页面:
- <%@ page language="java" pageEncoding="utf-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <script type="text/javascript" src="js/register.js"></script>
- </head>
- <body>
- <form>
- 用户名
- <input type="text" name="username" id="username" />
- <input type="button" value="提交" id="btn1"/>
- <div id="myDiv"></div>
- </form>
- </body>
- </html>
我们利用js给提交按钮绑定事件。js代码:
- var xmlhttp;
- window.onload = function()
- {
- var btn1 = document.getElementById("btn1");
- btn1.οnclick= loadXMLDoc;
- }
- function loadXMLDoc()
- {
- if (window.XMLHttpRequest)
- {// code for IE7+, Firefox, Chrome, Opera, Safari
- xmlhttp = new XMLHttpRequest();
- }
- else
- {// code for IE6, IE5
- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- //绑定回调函数
- xmlhttp.onreadystatechange = function()
- {
- if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
- {
- document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
- }
- }
- //取得输入的值
- var name = document.getElementById("username").value;
- //第一个参数表示post请求,第二个参数表示提交给AjaxServlet,第三个参数为true,表示异步请求
- xmlhttp.open("POST", "AjaxServlet", true);
- xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xmlhttp.send("name="+name);
- }
响应的servlet:
- package com.servlet;
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class AjaxServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request,response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- PrintWriter out = response.getWriter();
- String name = request.getParameter("name");
- System.out.println(name);
- if(name.equals("shizhan"))
- {
- out.write("用户名已经存在,请更换");
- }
- else
- {
- out.write("用户名可以使用");
- }
- out.flush();
- out.close();
- }
- }
结果页面:
输入sss,点击提交
输入shizhan,点击提交
来源:http://blog.csdn.net/linshizhan/article/details/7915939