servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(1);
List<String> userNames = Arrays.asList("AAA","BBB","CCC");
String userName = request.getParameter("userName");
String result = null;
if(userNames.contains(userName)){
System.out.println(2);
result = "<font color='red'>該用戶名已被使用</font>";
}else {
result = "<font color='green'>該用戶名可以使用</font>";
}
System.out.println(3);
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(result);
}
index.jsp
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.11.3.js/"></script>
<script type="text/javascript">
$(function(){
$(":input[name='username']").change(function(){
var val = $(this).val();
val = $.trim(val);
if(val!=""){
var url = "${pageContext.request.contextPath}/login";
var args = {"userName":val,"time":new Date()};
$.post(url,args,function(data){
$("#message").html(data);
});
}
});
});
</script>
</head>
<body>
<form action="" method="post">
UserName:<input type="text" name="username" />
<br/>
<div id="message"></div>
<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
xml:
<servlet>
<description>
</description>
<display-name>UserNameServlet</display-name>
<servlet-name>UserNameServlet</servlet-name>
<servlet-class>com.servlets.UserNameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserNameServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
怎麼多了個/在最後?手誤還是什麼?如果有/在後面是目錄了,應該是這個問題導致jquery加載不進去,最好用$.ajax配置error看是否執行到error,$.post只有200狀態才會執行success,只能用浏覽器開發工具看ajax返回結果
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.11.3.js/"></script>