• AJAX 和 JSON


    AJAX:
    1. 概念: ASynchronous JavaScript And XML 异步的JavaScript 和 XML
      1. 异步和同步:客户端和服务器端相互通信的基础上
      * 客户端必须等待服务器端的响应。在等待的期间客户端不能做其他操作。
       * 客户端不需要等待服务器端的响应。在服务器处理请求的过程中,客户端可以进行其他的操作。

    Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
    通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
    传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。

    原生实现方法

    html:
    
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script>
            
            //定义方法
            function  fun() {
                //发送异步请求
                //1.创建核心对象
                var xmlhttp;
                if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {// code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
    
                //2. 建立连接
                /*
                    参数:
                        1. 请求方式:GET、POST
                            * get方式,请求参数在URL后边拼接。send方法为空参
                            * post方式,请求参数在send方法中定义
                        2. 请求的URL:
                        3. 同步或异步请求:true(异步)或 false(同步)
    
                 */
                xmlhttp.open("GET","ajaxServlet?username=tom",true);
                // username=tom 参数
                //3.发送请求  把上面的请求发出
                xmlhttp.send();
    
                //4.接受并处理来自服务器的响应结果
                //获取方式 :xmlhttp.responseText
                //什么时候获取?当服务器响应成功后再获取
    
                //当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
                xmlhttp.onreadystatechange=function()
                {
                    //判断readyState就绪状态是否为4,判断status响应状态码是否为200
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                       //获取服务器的响应结果
                        var responseText = xmlhttp.responseText;
                        alert(responseText);
                    }
                }
    
            }
            
        </script>
        
        
    </head>
    <body>
    
        <input type="button" value="发送异步请求" onclick="fun();">
    
        <input>
    </body>
    </html>
    --------------------------------------------------------------------------------------------
    servlet:
    package cn.itcast.web.servlet;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

    @WebServlet("/ajaxServlet")
    public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.获取请求参数
    String username = request.getParameter("username");

    /* //处理业务逻辑。耗时
    try {
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }*/
    //2.打印username
    System.out.println(username);

    //3.响应
    response.getWriter().write("hello : " + username);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
    }
    }

    jquery  AJAX:

    jquery:
    <script>
            
            //定义方法
            function  fun() {
                //使用$.ajax()发送异步请求
    
                $.ajax({
                    url:"ajaxServlet1111" , // 请求路径
                    type:"POST" , //请求方式
                    //data: "username=jack&age=23",//请求参数
                    data:{"username":"jack","age":23},
                    success:function (data) {
                        alert(data);
                    },//响应成功后的回调函数
                    error:function () {
                        alert("出错啦...")
                    },//表示如果请求响应出现错误,会执行的回调函数
    
                    dataType:"text"//设置接受到的响应数据的格式
                });
            }
            
        </script>

    get

    <script>
            
            //定义方法
            function  fun() {
    
                $.get("ajaxServlet",{username:"rose"},function (data) {
                    alert(data);
                },"text");
    
            }
            
        </script>

    post

      <script>
            
            //定义方法
            function  fun() {
    
                $.post("ajaxServlet",{username:"rose"},function (data) {
                    alert(data);
                },"text");
    
            }
            
        </script>

    JSON

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script>
            //1.定义基本格式
            var person = {"name": "张三", age: 23, 'gender': true};
    
            //获取name的值
            //var name = person.name;
            var name = person["name"];
           // alert(name);
    
            //alert(person);
            //2.嵌套格式   {}———> []
            var persons = {
                "persons": [
                    {"name": "张三", "age": 23, "gender": true},
                    {"name": "李四", "age": 24, "gender": true},
                    {"name": "王五", "age": 25, "gender": false}
                    ],
                "persons1": [
                    {"name": "张三", "age": 23, "gender": true},
                    {"name": "李四", "age": 24, "gender": true},
                    {"name": "王五", "age": 25, "gender": false}
                ],
            };
           // alert(persons);
            //获取王五值
            var name1 = persons.persons[2].name;
           // alert(name1);
    
    
            //2.嵌套格式   []———> {}
            var ps = [{"name": "张三", "age": 23, "gender": true},
                {"name": "李四", "age": 24, "gender": true},
                {"name": "王五", "age": 25, "gender": false}];
            //获取李四值
            //alert(ps);
            alert(ps[1].name);
    
    
        </script>
    
    </head>
    <body>
    
    </body>
    </html>

    json 值得获取

    注意:一定要【  】  中间没有点

     for (var i = 0; i < ps.length; i++) {
                var p = ps[i];
                for(var key in p){
                    alert(key+":"+p[key]);
                }
            }

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    JSON  和 JAVA   的相互转换

    JSON数据和Java对象的相互转换
    
            * JSON解析器:
                * 常见的解析器:Jsonlib,Gson,fastjson,jackson
            
            1. JSON转为Java对象
                1. 导入jackson的相关jar包
                2. 创建Jackson核心对象 ObjectMapper
                3. 调用ObjectMapper的相关方法进行转换
                    1. readValue(json字符串数据,Class)
            2. Java对象转换JSON
                1. 使用步骤:
                    1. 导入jackson的相关jar包
                    2. 创建Jackson核心对象 ObjectMapper
                    3. 调用ObjectMapper的相关方法进行转换
                        1. 转换方法:
                            * writeValue(参数1,obj):
                                参数1:
                                    File:将obj对象转换为JSON字符串,并保存到指定的文件中
                                    Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                                    OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
                            * writeValueAsString(obj):将对象转为json字符串
    
                        2. 注解: 在类。java 文件里 属性上方添加
                            1. @JsonIgnore:排除属性。
                            2. @JsonFormat:属性值得格式化
                                * @JsonFormat(pattern = "yyyy-MM-dd")
    
                        3. 复杂java对象转换
                            1. List:数组
                            2. Map:对象格式一致

    -------------------------------------------------------------------------------------------

    json 练习

    ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(p);
    

     

    package cn.itcast.test;
    
    import cn.itcast.domain.Person;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Test;
    
    import java.io.FileWriter;
    import java.util.*;
    
    public class JacksonTest {
    
    
        //Java对象转为JSON字符串
        @Test
        public void test1() throws Exception {
            //1.创建Person对象
            Person p  = new Person();
            p.setName("张三");
            p.setAge(23);
            p.setGender("男");
    
            //2.创建Jackson的核心对象  ObjectMapper
            ObjectMapper mapper = new ObjectMapper();
            //3.转换
            /*
    
                转换方法:
                    writeValue(参数1,obj):
                        参数1:
                            File:将obj对象转换为JSON字符串,并保存到指定的文件中
                            Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                            OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
                    writeValueAsString(obj):将对象转为json字符串
    
             */
            String json = mapper.writeValueAsString(p);
            //{"name":"张三","age":23,"gender":"男"}
            //System.out.println(json);//{"name":"张三","age":23,"gender":"男"}
    
    
    
            //writeValue,将数据写到d://a.txt文件中
            //mapper.writeValue(new File("d://a.txt"),p);
    
            //writeValue.将数据关联到Writer中
            mapper.writeValue(new FileWriter("d://b.txt"),p);
        }
    
    
        @Test
        public void test2() throws Exception {
            //1.创建Person对象
            Person p = new Person();
            p.setName("张三");
            p.setAge(23);
            p.setGender("男");
            p.setBirthday(new Date());
    
    
    
            //2.转换
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(p);
    
            System.out.println(json);//{"name":"张三","age":23,"gender":"男","birthday":1530958029263}
                                    //{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}
        }
    
    
    
        @Test
        public void test3() throws Exception {
            //1.创建Person对象
            Person p = new Person();
            p.setName("张三");
            p.setAge(23);
            p.setGender("男");
            p.setBirthday(new Date());
    
            Person p1 = new Person();
            p1.setName("张三");
            p1.setAge(23);
            p1.setGender("男");
            p1.setBirthday(new Date());
    
            Person p2 = new Person();
            p2.setName("张三");
            p2.setAge(23);
            p2.setGender("男");
            p2.setBirthday(new Date());
    
    
            //创建List集合
            List<Person> ps = new ArrayList<Person>();
            ps.add(p);
            ps.add(p1);
            ps.add(p2);
    
    
            //2.转换
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(ps);
            // [{},{},{}]
            //[{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"},{"name":"张三","age":23,"gender":"男","birthday":"2018-07-07"}]
            System.out.println(json);
        }
    
        @Test
        public void test4() throws Exception {
            //1.创建map对象
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("name","张三");
            map.put("age",23);
            map.put("gender","男");
    
    
            //2.转换
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(map);
            //{"name":"张三","age":23,"gender":"男"}
            System.out.println(json);//{"gender":"男","name":"张三","age":23}
        }
    
        //演示 JSON字符串转为Java对象
        @Test
        public void test5() throws Exception {
           //1.初始化JSON字符串
            String json = "{"gender":"男","name":"张三","age":23}";
    
            //2.创建ObjectMapper对象
            ObjectMapper mapper = new ObjectMapper();
            //3.转换为Java对象 Person对象
            Person person = mapper.readValue(json, Person.class);
    
            System.out.println(person);
        }
    
    }

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    blur 事件   失去焦点事件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册页面</title>
        <script src="js/jquery-3.3.1.min.js"></script>
    
    
        <script>
            //在页面加载完成后
            $(function () {
               //给username绑定blur事件
               $("#username").blur(function () {
                   //获取username文本输入框的值
                   var username = $(this).val();
                   //发送ajax请求
                   //期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
                   //                         {"userExsit":false,"msg":"用户名可用"}
                   $.get("findUserServlet",{username:username},function (data) {
                       //判断userExsit键的值是否是true
    
                       // alert(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);
                       }
                   });
    
               }); 
            });
    
        </script>
    </head>
    <body>
    
    
        <form>
    
            <input type="text" id="username" name="username" placeholder="请输入用户名">
            <span id="s_username"></span>
            <br>
            <input type="password" name="password" placeholder="请输入密码"><br>
            <input type="submit" value="注册"><br>
    
        </form>
    
    </body>
    </html>
    -------------------------------------------------------------------------------------
    servlet:
    package cn.itcast.web.servlet;

    import com.fasterxml.jackson.databind.ObjectMapper;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;

    @WebServlet("/findUserServlet")
    public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.获取用户名
    String username = request.getParameter("username");

    //2.调用service层判断用户名是否存在

    //期望服务器响应回的数据格式:{"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"}
    // {"userExsit":false,"msg":"用户名可用"}

    //设置响应的数据格式为json
    response.setContentType("application/json;charset=utf-8");
    Map<String,Object> map = new HashMap<String,Object>();

    if("tom".equals(username)){
    //存在
    map.put("userExsit",true);
    map.put("msg","此用户名太受欢迎,请更换一个");
    }else{
    //不存在
    map.put("userExsit",false);
    map.put("msg","用户名可用");
    }

    //将map转为json,并且传递给客户端
    //将map转为json
    ObjectMapper mapper = new ObjectMapper();
    //并且传递给客户端
    mapper.writeValue(response.getWriter(),map);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
    }
    }
     
  • 相关阅读:
    【正则表达式】正则表达式基础语法
    【JavaWeb】实现二级联动菜单
    【JavaWeb】jQuery对Ajax的支持
    MySQL复习值代码知识点(2)
    easyUI+servlet+mysql项目总结
    Android环境配置(Eclipse全开发环境下载)
    jsp+servlet+mysql简单实现用户登陆注册
    java的异常抛出throws和throw的简单使用
    关于Java的多线程Runnable的个人理解(基础,不讲概念)
    Eclipse中代码自动添加注释及代码注释模板
  • 原文地址:https://www.cnblogs.com/qj696/p/13827508.html
Copyright © 2020-2023  润新知