案例
- 校验用户名是否存在
- 服务器响应的数据,在客户端使用时,要想当作json数据格式使用
- $.get(type):将最后一个参数tupe指定为"json"
- 在服务器端设施MIME类型
- response.setContentType("test/html;charset=utf-8");
- 服务器响应的数据,在客户端使用时,要想当作json数据格式使用
regist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script src="js/jquery-3.6.0.min.js"></script>
<script>
//在页面加载完成后执行
$(function () {
//给username绑定blur事件
$("#username").blur(function () {
//获取username输入框的值
var username = $(this).val();
//发送ajax请求
$.get("/findUserServlet", {username: username}, function (data) {
var span = $("#s_username");
if (data.userExsit) {
span.css("color", "red");
span.html(data.msg);
} else {
span.css("color", "green");
span.html(data.msg);
}
},"json");
});
});
</script>
</head>
<body>
<form>
用户名:<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username"></span>
<br><br>
密码:<input type="password" name="password" placeholder="密码"><br><br>
<input type="submit" value="注册">
</form>
</body>
</html>
FindUserServlet
package com.ailyt.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
@WebServlet(name = "findUserServlet", value = "/findUserServlet")
public class FindUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("test/html;charset=utf-8");
String username = request.getParameter("username");
HashMap<String, Object> map = new HashMap<>();
if ("tom".equals(username)) {
map.put("userExsit",true);
map.put("msg", "此用户名太受欢迎请换一个");
} else {
map.put("userExsit",false);
map.put("msg", "用户名可用");
}
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getWriter(),map);
}
}
标签:username,map,用户名,span,校验,案例,import,response
From: https://www.cnblogs.com/ailhy/p/16609909.html