JSON & Ajax

Ajax 和 Json

json

JavaScript 对象表示法(JavaScript Object Notation)

要求和语法格式

  • 对象表示为键值对
  • 数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

Json 与 js对象的关系

  • Json 是 js 对象的字符串表示法,使用文本表示一个js对象的信息,本质上就是一个字符串

  • Json 与 js对象互转

    • Json to js, 使用JSON.parse()

      let obj = JSON.parse('{"a":"Hello", "b":"World"}');
      
    • js to json, 使用JSON.stringify()

      let json = JSON.stringify({a:"Hello", b:"World"});
      
  • Servlet内返回json

    • 简单的一个对象
    @WebServlet("/json1")
    public class Demo1 extends HttpServlet {
        @Override
    
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            /*
             * ObjectMapping 是 jackson 操作的核心,所有JSON操作都在ObjectMapping中实现
             * ObjectMapping 有多个序列化的方法,可以把JSON字符串保存在File、outputStream中
             * writeValue(File arg0, Object arg1)可以把arg1转换为json序列保存到arg0文件中
             * writeValue(OutputStream arg0, Object arg1)可以把arg1转换为json序列,并输出到arg0输出流中
             * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组
             * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串
             */
            ObjectMapper objectMapper = new ObjectMapper();
            User user = new User("小明", 10, "男");
            String str = objectMapper.writeValueAsString(user);
            System.out.println(str);
            // 页面输出乱码
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print(str);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    • 时间类型数据
    @WebServlet("/json3")
    public class Demo3 extends HttpServlet {
        @Override
    
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 这里实现日期转换工具类封装工作
            resp.getWriter().print(TimeUtils.getTimeStr());
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    • 封装的工具类
    /**
     * @author Rainful
     * @create 2021/07/28
     */
    public class TimeUtils {
        /**
         * 获取当前时间的默认格式 yyyy-MM-dd HH:mm:ss
         * @return 一个时间字符串类型
         */
        public static String getTimeStr(){
            return getTimeStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        }
    
        /**
         * 获取一个指定时间的默认格式 yyyy-MM-dd HH:mm:ss
         * @param date 一个指定的时间
         * @return 一个时间字符串类型
         */
        public static String getTimeStr(Date date){
            return getTimeStr(date, "yyyy-MM-dd HH:mm:ss");
        }
    
        /**
         * 获取当前时间并按照格式指定的格式格式化
         * @return 一个时间字符串类型
         */
        public static String getTimeStr(String dateFormat) {
            return getTimeStr(new Date(), dateFormat);
        }
    
        /**
         * 获取指定时间并按照格式指定的格式格式化
         * @param date 一个指定的时间
         * @param dateFormat 指定的时间格式
         * @return 一个时间字符串类型
         */
        public static String getTimeStr(Date date, String dateFormat){
            // 日期转化需要关闭 ObjectMapping时间戳功能
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    
            // 自定义时间格式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
            objectMapper.setDateFormat(simpleDateFormat);
    
            // 获得时间并返回
            Calendar cal = Calendar.getInstance();
            try {
                return objectMapper.writeValueAsString(cal);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    

Ajax

Ajax 是一种在无需重新加载整个网页的前提下,局部刷新网页的一种技术

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <script src="../jquery/jquery-3.6.0.js"></script>
</head>
<body>
<h3>请输入要访问的地址</h3>
<p>
    <input type="text" id="url" placeholder="请输入网址" required />
    <input type="button" id="submit" value="提交" />
</p>
<h3>网页加载</h3>
<iframe width="100%" height="500px" id="iframeObj"></iframe>

<script type="text/javascript">
    let submitObj = $("#submit");
    let iframeObj = $("#iframeObj");
    let urlObj = $("#url");

    submitObj.click(
        function () {
            iframeObj.attr("src", urlObj.val());
        }
    )
</script>

</body>
</html>
  • 上面是一个虚假的 Ajax 形式
  • Ajax的核心就是XMLHttpRequest对象(XHR)
    • 这是使用jquery来实现
<!DOCTYPE html>
<html lang="en">
<head>
    <!--下面这行解决html乱码-->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>ajax</title>
    <script src="../jquery/jquery-3.6.0.js"></script>
</head>
<body>
<p>
    <label for="name">用户名</label><input type="text" id="name" onblur="a1()">
    <span id="nameInfo"></span>
</p>
<p>
    <label for="pwd">密码</label><input type="password" id="pwd" onblur="a2()">
    <span id="pwdInfo"></span>
</p>

<script>
    function a1() {
        $.post(
            "../ajax3", {"name": $("#name").val()}, function (data) {
                let $nameInfo = $("#nameInfo");
                console.log(data);
                if (data === "ok") {
                    $nameInfo.css("color","green");
                } else {
                    $nameInfo.css("color","red");
                }
                console.log(typeof data)
                $nameInfo.html(data);
            }
        )
    }
    function a2() {
        $.post(
            "../ajax3", {"pwd": $("#pwd").val()}, function (data) {
                let $pwdInfo = $("#pwdInfo");
                console.log(data);
                if (data === "ok") {
                    $pwdInfo.css("color","green");
                } else {
                    $pwdInfo.css("color","red");
                }
                console.log(typeof data)
                $pwdInfo.html(data);
            }
        )
    }
</script>

</body>
</html>
@WebServlet("/ajax3")
public class AjaxServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        Map<String, String[]> parameterMap = req.getParameterMap();
        String msg = "";

        // 验证用户名及密码
        if (!parameterMap.isEmpty()) {
            String[] name = parameterMap.get("name");
            if (name != null) {
                if ("admin".equals(name[0])) {
                    System.out.println("用户名验证成功");
                    msg = "ok";
                } else {
                    System.out.println("用户名验证失败");
                    msg = "用户名输入有误";
                }
            }

            String[] pwd = parameterMap.get("pwd");
            if (pwd != null) {
                if ("123456".equals(pwd[0])) {
                    System.out.println("密码验证成功");
                    msg = "ok";
                } else {
                    System.out.println("密码验证失败");
                    msg = "密码输入有误";
                }
            }
        }

        resp.getWriter().print(msg);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
posted @ 2021-07-28 23:11  Rainful  阅读(28)  评论(0编辑  收藏  举报