Ajax验证用户名是否存在


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax实现验证用户名</title>
<script type="text/javascript" src="JS/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function() {
$("input[name=userName]").blur(function() {
var name = $(this).val();
if (null == name || "" == name) {
$("#msg").html("用户名不能为空");
return;
}
//使用呢jQueryAjax实现用户名验证
$.ajax({
url : "CheckUserNameServlet",//
type : "post",
data : {
"name" : name //这个是得到了index界面输入框的值
},
dataType : "JSON",
success : function(reault) {
var flag = reault.flag;
if ("true" == flag) {
$("#msg").html("可用的用户名!!");
} else {
$("#msg").html("已经使用的用户名");
}
}
});
});
});
</script>
</head>


<body>
用户名:
<input type="text" id="userName" name="userName" />
<span id="msg"></span>
</body>
</html>


Servlet

package 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 CheckUserNameServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset:utf-8");
String name=request.getParameter("name");
PrintWriter out = response.getWriter();
if ("admin".equals(name)||"张三".equals(name)) {
out.print("{\"flag\":\"false\"}");
}else{
out.print("{\"flag\":\"true\"}");
}
out.flush();
out.close();
}


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

doGet(request, response);
}

}