用AJAX简单实现注册页面的用户名检测
js代码:
<script>
// **原生的方式使用AJAX**
// function getXMLHttpRequest(){
// if(window.XMLHttpRequest){
// return new XMLHttpRequest();
// }
// }
// var xhr;
// function inputLogin(text){
// xhr = getXMLHttpRequest();
// var loginId = text.value;
// xhr.onreadystatechange = rFunction;
// xhr.open("GET", "admin?loginId="+loginId, true);
// xhr.send(null);
// }
// function rFunction(){
// var s = document.getElementById("s");
// if(xhr.readyState == 4){
// if(xhr.status == 200){
// var data = xhr.responseText;
// if(data == "yes"){
// s.innerHTML = "可以注册";
// s.style.color = "green";
// }else{
// s.innerHTML = "已注册";
// s.style.color = "red";
// }
// }
// }
// }
// **使用jQuery实现AJAX**
function inputLogin(text){
var loginId = $("#loginId").val();
var s = $("#s");
// **使用JQuery的一般写法**
// $.ajax({
// type:"POST",
// url:"admin",
// data:"loginId="+loginId,
// dataType:"text",
// success:function(msg){
// if(msg == "yes"){
// s.css("color", "green").html("可以注册..");
// }else if(msg == "no"){
// s.css("color", "red").html("已经注册..");
// }else{
// s.html("请写用户名");
// }
// }
// });
// **使用jQuery的简洁写法**
$.post(
"admin",
{loginId:loginId},
function(msg){
if(msg == "yes"){
s.css("color", "green").html("可以注册..");
}else if(msg == "no"){
s.css("color", "red").html("已经注册..");
}else{
s.html("请写用户名");
}
},
"text"
)
}
</script>
html代码:
<body>
<a href="StudentServlet">学员列表</a>
<form action="test" method="post">
用户名:<input type="text" id="loginId" name="loginId" onblur="inputLogin(this)"><span id="s"></span><br>
密码:<input type="password" name="loginPwd">
<button type="submit">submit</button>
</form>
</body>
servlet代码:
@WebServlet("/admin")
public class AdminServlet extends HttpServlet{
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
String loginId = req.getParameter("loginId");
//System.out.println("id"+loginId);
if(loginId!=null && !loginId.equals("")){
if(new AdminService().getAdminById(loginId)!=null){
res.getWriter().write("no");
}else{
res.getWriter().write("yes");
}
}
}
}