• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

异步数据交互ajax和axios

武飞扬头像
神也顾我萧何
帮助1

AJAX 与Axios

一、案例准备

  • 本次使用一个简单的登录来测试ajax与axios(使用javaweb开发测试)

  • 话不多说,上代码

1、首先数据库必不可少

  • 很多字段基本没用上,可以忽略不及,只要用户名密码即可
-- auto-generated definition

create table users
(
    id       varchar(50)   not null
        primary key,
    name     varchar(50)   not null comment '姓名',
    age      int           null comment '年龄',
    sex      int default 1 null comment '性别,1代表男,0代表女默认男,',
    password varchar(20)   not null,
    check (`sex` in (0, 1))
)
    charset = utf8;


2、实体类紧跟其后

public class User {

    private String id;
    private String name;
    private String password;
    private int age;
    private int sex;
}
//此处省略了getter和setter方法以及构造等其他方法

3、然后就是数据库访问层

  • 数据库连接的工具类
public class JdbcUtils {

    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&charsetEncoding=utf-8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static Connection con = null;
    private static Statement stm = null;
    private static ResultSet rs = null;

    /**
     * @return
     * 获取连接
     */
    public static Connection getCon() {
        try {
//            1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
//            2.加载连接
            con = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }


    /**
     * @param sql
     * @return
     * 公共增删改的方法,因为增删改对行影响,所以返回row
     */

    public static int update(String sql) {
        int row = 0;
        try {
            if (con == null) {
                con = getCon();
            }
            stm = con.createStatement();
            row = stm.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }


    /**
     * @param sql
     * @return
     * 查询的方法
     */
    public static ResultSet query(String sql) {
        try {
            if (con == null) {
                con = getCon();
            }
            stm = con.createStatement();
            rs = stm.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     *
     * @param connection
     * @param statement
     * @param resultSet
     * 关闭连接,释放资源
     */
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

学新通
  • 数据库访问层,没有写接口,直接写的简单化开发
public class UserDao {

    /**
     * 
     * @param sql
     * @return
     * 封装的是一个集体查数据的私有方法
     */
    private List<User> get(String sql) {
        ResultSet resultSet = JdbcUtils.query(sql);

        List<User> list = new ArrayList<>();
        User user;
        try {
            while (resultSet.next()) {
                user = new User();
                user.setId(resultSet.getString("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                user.setSex(resultSet.getInt("sex"));
                user.setPassword(resultSet.getString("password"));
                list.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeAll(null, null, resultSet);
        }
        return list;
    }

    /**
     * 
     * @param username 用户名
     * @param password 密码
     * @return
     * 登录方法,简单实现一下,
     */
    public boolean login(String username, String password) {
        String sql = "SELECT * FROM users WHERE name='"   username   "' AND password='"   password   "'";
        List<User> list = get(sql);
        if (list == null || list.isEmpty()) {
            return false;
        }
        System.out.println(list);
        return true;
    }
}
学新通

4、直接servlet类

  • 这里我直接省略了service层
@WebServlet(urlPatterns = "/user")
public class UserController extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println(username   "---doGet---"   password);

        UserDao userDao = new UserDao();
        boolean login = userDao.login(username, password);
        System.out.println(login);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      /*
      //        字节流,中文乱码
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        String str = null;
        while ((len = inputStream.read(bytes)) != -1) {
            str = new String(bytes, 0, len);
        }
        System.out.println("str-----"   str);
//        字符流和字节流获取数据任取一种都可,不过字节流中文乱码,建议使用字符流
        */

/*
//        设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
*/

//        使用字符流读取数据
        BufferedReader reader = request.getReader();
        char[] buf = new char[1024];
        int len = 0;
//        StringBuilder str = new StringBuilder();
        StringBuffer str = new StringBuffer();
        while ((len = reader.read(buf)) != -1) {
            str.append(buf, 0, len);
        }
        UserDao userDao = new UserDao();
//        将前端获取到的StringBuffer对象转成String
        String s = String.valueOf(str);
        System.out.println("str====="   str "--------\ts=====" s);

//        先判空,在判断是不是JSON格式
        if (s != null) {
            if (JSONObject.isValid(s)) {
//        转换为JSON格式
                JSONObject jsonObject = JSONObject.parseObject(s);
                String username = jsonObject.getString("username");
                String password = jsonObject.getString("password");
                System.out.println(username   "---doPost---"   password);
                boolean login = userDao.login(username, password);
                System.out.println(login);
            }else {
                System.out.println("数据格式有问题,用户名密码默认为空");
                boolean login = userDao.login(null, null);
                System.out.println(login);
            }
        }
    }

}

学新通
  • 因为在dopost方法中post请求不携带数据,所以使用request.getParameter();获取不到数据,这时候就需要使用到数据流了。

  • 上面dopost中使用的是字符流获取数据

  • 下面是字节流获取数据,因为字节流获取数据,中文会乱码,所以一般使用字符流

/* 
   @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        字节流,中文乱码
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        String str = null;
        while ((len = inputStream.read(bytes)) != -1) {
            str = new String(bytes, 0, len);
        }
        System.out.println("str-----"   str);
        String[] data = str.split(",");
        for (String datum : data) {
            System.out.println(datum);
        }

    }
*/
学新通

5、过滤器

  • @WebFilter(urlPatterns = "/*")这是拦截全部的请求,然后将字符编码处理过后才放行
@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String method = request.getMethod();
        System.out.println(method);

        //判断是post方法,设置编码
        if ("POST".equals(method)) {
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setContentType("text/html; charset=UTF-8");
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }

}

学新通

5、注意一点

Get和post都能够提交数据,那么他们有什么不同呢?

  • 不同点一:

    通过get方式提交的数据有大小的限制,通常在1024字节左右。也就是说如果提交的数据很大,用get方法就可需要小心;而post方式没有数据大小的限制,理论上传送多少数据都可以。

  • 不同点二:

    通过get传递数据,实际上是将传递的数据按照”key,value”的方式跟在URL的后面来达到传送的目的的;而post传递数据是通过http请求的附件进行的,在URL中并没有明文显示。

  • 不同点三:

    通过Get方式提交的数据安全性不高,而Post方式的更加安全~

二、原生的ajax请求

  • 登录页面代码内容基本相同 也可忽略不计,使用一个即可

1、原生的使用XMLHttpRequest对象获取的异步操作

//发送同步请求
        //1.创建ajax引擎对象----所有操作都是由ajax引擎完成
        var xmlHttp = new XMLHttpRequest();
        //2.为引擎对象绑定监听事件
        xmlHttp.onreadystatechange = function() {
            //当状态变化时处理的事情
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                //5.接收响应信息
                var data = xmlHttp.responseText;
                //alert(data);
                document.getElementById("span2").innerHTML=data;
            }
        }
        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步
        xmlHttp.open("GET", "http://localhost:8099/ajax_demo/user"
            false);
        //4.发送请求
        xmlHttp.send();

        // 在JS原生Ajax中,也可以指定 如果是post提交
        // 在发送请求之前设置一个头
        // xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		//xmlHttp.send(data);

学新通

2、看原生ajax在实例中用法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原生ajax(通过XMLHttpRequest对象)登录</title>

    <!--
    使用原生ajax异步传输数据
    -->
</head>
<body>
<div id="loginFrom" style="margin: 20% 30%">
    <input type="text" name="username" placeholder="用户名" class="params"><br>
    <input type="text" name="password" placeholder="密码" class="params"><br>
    <input type="submit" value="get登录" onclick="loginGet()">
    <input type="submit" value="post登录" onclick="loginPost()">

    <div class="result" width="10px" height="10px"></div>
</div>

<script>

    function loginGet() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;

        //1.创建ajax引擎对象
        let xmlHttpRequest = new XMLHttpRequest();

        console.log("-------get===="   "username="   username   ",password="   password)
        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步

        xmlHttpRequest.open("GET", "http://localhost:8099/ajax_axios_demo/user?username="   username   "&password="   password, true);
        xmlHttpRequest.send();

        //2.为引擎对象绑定监听事件
        xmlHttpRequest.onreadystatechange = function () {
            //当状态变化时处理
            if (xmlHttpRequest.status == 200 && xmlHttpRequest.readyState == 4) {
                //接收响应数据
                let data = xmlHttpRequest.responseText;
                console.log("-----"   data);
            } else {
                console.log("error!")
            }
        }
    }

    function loginPost() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;

        //1.创建ajax引擎对象
        let xmlHttpRequest = new XMLHttpRequest();

        console.log("-------post===="   "username="   username   ",password="   password)

        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步
        xmlHttpRequest.open("POST", "http://localhost:8099/ajax_axios_demo/user", true);
        xmlHttpRequest.setRequestHeader("Content-type", "application/json;charset=utf-8");
        //4.发送请求
        xmlHttpRequest.send("{'username':'"   username   "','password':'"   password "'}");

        // 在JS原生Ajax中,也可以指定 如果是post提交
        // 在发送请求之前设置一个头
        //2.为引擎对象绑定监听事件
        xmlHttpRequest.onreadystatechange = function () {
            //当状态变化时处理
            if (xmlHttpRequest.status == 200 && xmlHttpRequest.readyState == 4) {
                //接收响应数据
                let data = xmlHttpRequest.responseText;
                console.log("-----"   data);
            } else {
                console.log("error!")
            }
        }
    }

    function login() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;
        //1.创建ajax引擎对象
        let xmlHttpRequest = new XMLHttpRequest();
        //2.为引擎对象绑定监听事件
        xmlHttpRequest.onreadystatechange = function () {
            //当状态变化时处理
            if (xmlHttpRequest.status == 200 && xmlHttpRequest.readyState == 4) {
                //接收响应数据
                let data = xmlHttpRequest.responseText;
                console.log("-----"   data);
            } else {
                console.log("error!")
            }
        }

        console.log("-------===="   "username="   username   ",password="   password)
        xmlHttpRequest.open("GET", "http://localhost:8099/ajax_axios_demo/user?username="   username   "&password="   password, true);
        xmlHttpRequest.send();

        //3.绑定服务器地址
        //第一个参数:请求方式GET/POST
        //第二个参数:后台服务器地址
        //第三个参数:是否是异步 true--异步   false--同步
        // xmlHttpRequest.open("POST", "http://localhost:8099/ajax_axios_demo/user?username=admin&password=123456", true);
        // xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //4.发送请求
        // xmlHttpRequest.send();

        // 在JS原生Ajax中,也可以指定 如果是post提交
        // 在发送请求之前设置一个头
    }
</script>

</body>
</html>
学新通

三、AJAX

1、先导入jQuery.js

  • 由官网https://jquery.com/download/可知

  • 首先需要导入

<script src="https://unpkg.com/axios/dist/jQuery.min.js"></script>

2、看jQuery封装的ajax在实例中用法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基于jQuery的ajax登录</title>
    <!--
        使用jQuery.js封装的ajax
        -->
</head>
<body>
<div id="loginFrom" style="margin: 20% 30%">
    <input type="text" name="username" placeholder="用户名" class="params"><br>
    <input type="text" name="password" placeholder="密码" class="params"><br>
    <input type="submit" value="get登录" onclick="loginGet()">
    <input type="submit" value="post登录" onclick="loginPost()">

    <div class="result" width="10px" height="10px"></div>

    <script src="static/jquery-3.6.0.min.js"></script>

    <script>

        function loginGet() {
            let username = document.getElementsByName("username")[0].value;
            let password = document.getElementsByName("password")[0].value;
            console.log("-------get--------")
            $.ajax({
                method: 'GET',
                // url:'http://localhost:8099/ajax_demo/user?username=' username '&password=' password,
                url: 'http://localhost:8099/ajax_demo/user',
                data: {
                    username: username,
                    password: password
                }
            }).then(response => {
                console.log(response.data)
            }).catch(error => {
                console.log(error.data);
            });

        };

        function loginPost() {

            let username = document.getElementsByName("username")[0].value;
            let password = document.getElementsByName("password")[0].value;
            console.log("-------post--------");
            $.ajax({
                method: 'POST',
                url: 'http://localhost:8099/ajax_demo/user',
                data: {
                    username: username,
                    password: password
                }
            }).then(response => {
                console.log(response.data);
            }).catch(error => {
                console.log(error.data);
            });
        }

    </script>
</div>
</body>
</html>
学新通

四、Axios

1、先导入axios.js

  • 由官网可知

  • 首先需要导入

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


//由于发送的是json字符串,get携带数据使用常规方法接受可以,但post不携带数据,故需用键值对接收

2、看axios在实例中用法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基于axios登录</title>

    <!--
        使用axios发送异步请求
        -->

</head>
<body>
<div id="loginFrom" style="margin: 20% 30%">
    <input type="text" name="username" placeholder="用户名" class="params"><br>
    <input type="text" name="password" placeholder="密码" class="params"><br>
    <input type="submit" value="get登录" onclick="loginGet()">
    <input type="submit" value="post登录" onclick="loginPost()">

    <div class="result" width="10px" height="10px"></div>
</div>


<script src="static/axios.js"></script>

<script>

    function loginGet() {
        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;
        console.log("-------get--------")
        axios.get('http://localhost:8099/ajax_axios_demo/user',
            {
                params: {
                    username: username,
                    password: password
                },
            }).then(response => {
            console.log(response.data)
        }).catch(error => {
            console.log(error.data);
        });
    }

    function loginPost() {

        let username = document.getElementsByName("username")[0].value;
        let password = document.getElementsByName("password")[0].value;
        console.log("-------post--------");
        axios({
            method: 'post',
            // url:'/user',
            url: 'http://localhost:8099/ajax_axios_demo/user',
            data: {
                username: username,
                password: password
            }
        }).then(response => {
            console.log(response.data);
        }).catch(error => {
            console.log(error.data);
        });
    }

</script>

</body>
</html>
学新通

3、基于Vue的axios

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>基于Vue的axios登录</title>
    <!--
        基于Vue的axios异步请求
        -->
        <script src="static/vue-2.6.14.js"></script>
<!--    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>-->


</head>
<body>
<div id="app">
    <div id="loginFrom" style="margin: 20% 30%">
        <input v type="text" placeholder="用户名" v-model="username"><br>
        <input type="text" placeholder="密码" v-model="password"><br>
        <input type="submit" value="get登录" @click="loginGet">
        <input type="submit" value="post登录" @click="loginPost">

    </div>
</div>

<script src="static/axios.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            username: '',
            password: ''
        },
        methods: {
            loginGet() {
                console.log("-------get--------")
                axios.get('http://localhost:8099/ajax_axios_demo/user',
                    {
                        params: {
                            username: this.username,
                            password: this.password
                        },
                    }).then(response => {
                    console.log(response.data)
                }).catch(error => {
                    console.log(error.data);
                });
            },
            loginPost() {
                console.log("-------post--------");
                axios({
                    method: 'post',
                    url: 'http://localhost:8099/ajax_axios_demo/user',
                    data: {
                        username: this.username,
                        password: this.password
                    }
                }).then(response => {
                    console.log(response.data);
                }).catch(error => {
                    console.log(error.data);
                });
            }
        }
    });

</script>
</body>
</html>
学新通
  • 原代码在gitee上https://gitee.com/xiaohe2323/ajax_axios_demo.git

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfcgaj
系列文章
更多 icon
同类精品
更多 icon
继续加载