我的代码如下所示
<%@ 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">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/myJS.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
window.onload=function(){
var nameElement=document.getElementsByName("userName");
nameElement.onblur=function(){
var name=this.value;
var xrl=getXMLHttpRequest();
xrl.onreadystatechange=function(){
if(xrl.readyState==4&&xrl.status==200){
var msg=document.getElementById("msg");
if(xrl.responseText=="true"){
msg.innerText="<font color='red'>用户名已存在</font>";
}else{
msg.innerHTML="用户名可以使用";
}
}
}
xrl.open("get","${pageContext.request.contextPath}/servlet/ckNameServlet?name="+name);
xrl.send(null);
}
}
</script>
</head>
<body>
用户名:<input type="text" name="userName" /><span id="msg"></span><br/>
密码:<input type="password" name="password"/><br/>
</body>
</html>
servlet代码如下
public class CkNameServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
if("tom".equals(name)){
out.print(true);
}else{
out.print(false);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
显示结果:输入tom后没有任何效果
1.输入name以后鼠标焦点离开Input输入框了吗
2.条件1满足以后,进入onblur事件了吗(打断点或者在事件alert一下)
3.满足2以后,ajax请求成功了吗(通过F12在浏览器监听一下,看数据是否成功发起了请求,如果失败,返回的状态码是多少)
谢谢,我找到问题了,var nameElement=document.getElementsByName("userName");这行代码应该改为var nameElement=document.getElementsByName("userName")[0];
前端不大懂,但是servlet里面没有转发也没有重定向,然后你输出的是boolean值而不是将定义一个msg然后存到request域里面,页面再接收。
String name = request.getParameter("name");//取值
boolean msg=false;//声明
if("tom".equals(name)){
msg=true;//若满足条件
request.setAttribute("msg",msg);//存值
request.getRequestDispatcher("成功目标页").forward(request, response);//重定向
}else{
request.setAttribute("msg",msg);
request.getRequestDispatcher("回到登录页").forward(request, response);
}