1.首先看看JQuery给我们提供的文档

 

2.那我们如何知道响应json数据的MiME类型该怎么写?

 

3.后台+前端代码如下

 

 

 

*源代码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="js/jquery-3.3.1.min.js"></script>
 7     <script>
 8         $(function () {
 9             $("#usernameId").blur(function () {
10                 $.post({
11                     url: "ajaxRegisterServlet",
12                     data: {"username": $("#usernameId").val(), "password": $("#passwordId").val()},
13                     success: function (data) {
14                         alert(data);
15                         $("#spanId1").text(data.msg);
16                     },
17                 });
18             });
19         });
20     </script>
21 </head>
22 <body>
23 <from>
24     用户名:<input type="text" name="username" id="usernameId">
25     <span id="spanId1"></span>
26     <br/>
27     密码: <input type="password" name="password" id="passwordId">
28 </from>
29 </body>
30 </html>

 1 package com.cht.web.servlet;
 2 
 3 import com.fasterxml.jackson.databind.ObjectMapper;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 import java.util.HashMap;
12 import java.util.Map;
13 
14 /**
15  * Created by IntelliJ IDEA.
16  *
17  * @author chenhaitao
18  * Date: 2019/7/8
19  * Time: 13:16
20  */
21 
22 @WebServlet(name = "ajaxRegisterServlet", urlPatterns = "/ajaxRegisterServlet")
23 public class AjaxRegisterServlet extends HttpServlet {
24     @Override
25     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
26         request.setCharacterEncoding("utf-8");
27         response.setContentType("application/json;charset=utf-8");
28         String username = request.getParameter("username");
29         System.out.println(username);
30         Map<String, Object> map = new HashMap<>();
31 
32         if ("cht".equals(username)) {
33             map.put("userExist", true);
34             map.put("msg", "用户名已存在");
35         } else {
36             map.put("userExist", false);
37             map.put("msg", "用户名可用");
38         }
39         System.out.println(new ObjectMapper().writeValueAsString(map));
40 
41         new ObjectMapper().writeValue(response.getOutputStream(), map);
42     }
43 }