---
title: "通用的Ajax模板 校验用户名"
author: "gzd3618"
date: "2009-08-13T09:09:20Z"
tags: ["Ajax", "JSP", "JavaScript", "Microsoft", "Servlet"]
slug: "ajax"
draft: false
lastmod: "2009-08-13T09:09:20Z"
id: 446017
url: "https://gzd3618.iteye.com/blog/446017"
---

\[b]校验用户名是否存在\[/b] \[b]Ajax.js\[/b] \[code="javascript"]var \_xmlHttpRequestObj; var \_loadingFunction; var \_postHttpProcessChangeCallback; var resultValue; function postXmlHttp(submiturl,callbackfunc,loadfunc) { \_postHttpProcessChangeCallback = callbackfunc; \_loadingFunction=loadfunc; if(window.createRequest) { \_xmlHttpRequestObj = window.createRequest(); \_xmlHttpRequestObj.open('POST',submiturl,true); \_xmlHttpRequestObj.onreadystatechange=postXmlHttpProcessPostChange; \_xmlHttpRequestObj.send(); }else if(window.XMLHttpRequest) { \_xmlHttpRequestObj = new XMLHttpRequest(); \_xmlHttpRequestObj.overrideMimeType('text/xml'); \_xmlHttpRequestObj.open('POST',submiturl,true); \_xmlHttpRequestObj.onreadystatechange=postXmlHttpProcessPostChange; \_xmlHttpRequestObj.send(""); }else if(window.ActiveXObject) { \_xmlHttpRequestObj = new ActiveXObject("Microsoft.XMLHTTP"); \_xmlHttpRequestObj.open('POST',submiturl,true); \_xmlHttpRequestObj.onreadystatechange=postXmlHttpProcessPostChange; \_xmlHttpRequestObj.send(); } } function postXmlHttpProcessPostChange() { if(\_xmlHttpRequestObj.readyState==4&&\_xmlHttpRequestObj.status==200) { resultValue = \_xmlHttpRequestObj.responseText; setTimeout(\_postHttpProcessChangeCallback,2); } if(\_xmlHttpRequestObj.readyState==1) { setTimeout(\_loadingFunction,2); } }\[/code] \[b]JSP页面\[/b] \[code="html"]&lt;%@ page language="java" pageEncoding="utf-8"%&gt; &lt;% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %&gt;  AjaxApp

用户名 密 码

\[/code] \[b]Serlet类\[/b] \[code="java"]public class UserServlet extends HttpServlet { /\** * Destruction of the servlet.  
\*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = (String)request.getParameter("userName"); UserService userService = new UserService(); boolean b = userService.checkUserName1(userName); response.setCharacterEncoding("utf-8"); //jsp页面编码最好也用utf-8 防止乱码 PrintWriter pw= response.getWriter(); if(b) { pw.write("该用户名已经被使用"); }else { pw.write("该用户名可用"); } } }\[/code]