AJAX - JSON


Javaweb - day12 - Filter&Listener&AJAX

AJAX

AJAX

  • 概念:AJAX,异步的JavaScript和XML

AJAX作用

  • 与服务器进行数据交换:通过AJAX可以给服务器发送请求,并获取服务器响应的数据。
  • 使用了AJAX和服务器进行通信,就可以使用HTML+AJAX来替换JSP页面了
  • 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用校验,等等....

同步和异步

AJAX快速入门

实例(ajaxServlet)

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 响应数据
        response.getWriter().write("hello ajax~");
    }

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

实例2(01-ajax-demo1.html)(创建核心对象可以再网上直接复制)

<script>
    //1. 创建核心对象
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2. 发送请求
    xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
    xhttp.send();

    //3. 获取响应
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
               alert(this.responseText);
        }
    };

</script>

案例(使用AJAX验证用户名是否存在)

实例(selectUserServlet)

@WebServlet("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. 接收用户名
        String username = request.getParameter("username");

        //2. 调用service查询User对象

        boolean flag = true;

        //3. 响应标记
        response.getWriter().write("" + flag);


    }

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

实例(register.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎注册</title>
    <link href="css/register.css" rel="stylesheet">
</head>
<body>

<div class="form-div">
    <div class="reg-content">
        <h1>欢迎注册</h1>
        <span>已有帐号?</span> <a href="login.html">登录</a>
    </div>
    <form id="reg-form" action="#" method="get">

        <table>

            <tr>
                <td>用户名</td>
                <td class="inputs">
                    <input name="username" type="text" id="username">
                    <br>
                    <span id="username_err" class="err_msg" style="display: none">用户名已存在</span>
                </td>

            </tr>

            <tr>
                <td>密码</td>
                <td class="inputs">
                    <input name="password" type="password" id="password">
                    <br>
                    <span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
                </td>
            </tr>


            <tr>
                <td>验证码</td>
                <td class="inputs">
                    <input name="checkCode" type="text" id="checkCode">
                    <img src="imgs/a.jpg">
                    <a href="#" id="changeImg">看不清?</a>
                </td>
            </tr>

        </table>

        <div class="buttons">
            <input value="注 册" type="submit" id="reg_btn">
        </div>
        <br class="clear">
    </form>

</div>

<script>

    //1. 给用户名输入框绑定 失去焦点事件
    document.getElementById("username").onblur = function () {
        //2. 发送ajax请求
        // 获取用户名的值
        var username = this.value;

        //2.1. 创建核心对象
        var xhttp;
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //2.2. 发送请求
        xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username);
        xhttp.send();

        //2.3. 获取响应
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //alert(this.responseText);
                //判断
                if(this.responseText == "true"){
                    //用户名存在,显示提示信息
                    document.getElementById("username_err").style.display = '';
                }else {
                    //用户名不存在 ,清楚提示信息
                    document.getElementById("username_err").style.display = 'none';
                }
            }
        };

    }


</script>
</body>
</html>

Axios异步框架

  • Axios 对原生的AJAX进行封装,简化书写。

Axios异步框架-快速入门

实例(02-axios-demo.html)

<script src="js/axios-0.18.0.js"></script>

<script>
    //1. get
   axios({
        method:"get",
        url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })


    //2. post
    axios({
        method:"post",
        url:"http://localhost:8080/ajax-demo/axiosServlet",
        data:"username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })
    
</script>

实例2(axiosServlet)

@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get...");

        //1. 接收请求参数
        String username = request.getParameter("username");
        System.out.println(username);

        //2. 响应数据
        response.getWriter().write("hello Axios~");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post...");
        this.doGet(request, response);
    }
}

Axios请求方式别名

  • 为了方便起见,Axios已经为所有支持的请求方法提供了别名。

实例

<script src="js/axios-0.18.0.js"></script>

<script>
    //1. get
   /axios({
        method:"get",
        url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })

    axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
        alert(resp.data);
    })



    //2. post
    axios({
        method:"post",
        url:"http://localhost:8080/ajax-demo/axiosServlet",
        data:"username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })

   axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
        alert(resp.data);
    })


    var jsObject = {name:"zhangsan"};

    axios({
        method:"post",
        url:"http://localhost:8080/ajax-demo/axiosServlet",
        data:jsObject
    }).then(function (resp) {
        alert(resp.data);
    })

</script>

JSON

JSON基础语法

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


<script>
  //1. 定义JSON字符串
  var jsonStr = '{"name":"zhangsan","age":23,"addr":["北京","上海","西安"]}';
  //alert(jsonStr);
  //2. 将JSON字符串转为JS对象
  let jsObject = JSON.parse(jsonStr);
  //alert(jsObject);
  let name = jsObject.name;
  //alert(name);

  //3. JS对象转为JSON字符串
  let jsonStr2 = JSON.stringify(jsObject);
  alert(jsonStr2)

</script>

</body>
</html>

JSON数据和Java对象转换

  • 请求数据:JSON字符串转为Java对象
  • 响应数据:Java对象转为JSON字符串

Fastjson

实例(导坐标)

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

实例(Java对象转换)(user类自己写)

package com.itheima.json;

import com.alibaba.fastjson.JSON;

public class FastJsonDemo {

    public static void main(String[] args) {
        //1. 将Java对象转为JSON字符串
        User user = new User();
        user.setId(1);
        user.setUsername("zhangsan");
        user.setPassword("123");

        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);//{"id":1,"password":"123","username":"zhangsan"}


        //2. 将JSON字符串转为Java对象

        User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class);
        System.out.println(u);


    }
}

声明:三二一的一的二|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - AJAX - JSON


三二一的一的二