$(function () {
$("#username").blur(function () {
// 获取用户名
var username = this.value;
$.getJSON("http://localhost:8080/userServlet","action=ajaxExistsUsername&username="+username,function (data) {
console.log(data);
if (data.existsUsername){
$("span.errorMsg").text("ajax技术表明用户名已存在")
}else {
$("span.errorMsg").text("ajax表明用户名可用")
}
})
});
<span class="errorMsg">
${requestScope.msg==null?"":requestScope.msg}
</span>
在UserServlet中
public void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
boolean existsUsername = userService.existsUsername(username);
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("existsUsername",existsUsername);
Gson gson = new Gson();
String json = gson.toJson(resultMap);
resp.getWriter().write(json);
}