自学内容网 自学内容网

Ajax和axios简单用法

Ajax

Ajax(Asynchronous JavaScript And XML,异步的JavaScript和XML)。

作用是:

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

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

</head>
<body>
    <input type="button" value="获取数据" onclick="getClick()">
</body>
<script>
    function getClick() {
        // 创建一个XMLHttpRequest对象
        let XmlHttpRequest = new XMLHttpRequest();
        
        // 设置请求方式和请求地址
        XmlHttpRequest.open('GET', 'http://yapi.smart-xwork.cn/mock/169327/emp/list');
        XmlHttpRequest.send(); // 发送请求

        // 监听请求状态
        XmlHttpRequest.onreadystatechange = function() {
            if (XmlHttpRequest.readyState === 4 && XmlHttpRequest.status === 200) {
                // console.log(XmlHttpRequest.responseText);
                let data = JSON.parse(XmlHttpRequest.responseText);
                console.log(data);
            }
        }
    }
</script>
</html>

Axios

Axios对原生的Ajax进行了封装,简化书写,快速开发。

需要引入Axios的JS文件,使用Axios发送请求,并获取响应结果。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <script>
        axios({
            method: 'get',
            url: 'http://localhost:3000/lab'
        }).then((response) => {
            console.log(response.data)
        });
        axios({
            method: 'post',
            url: 'http://localhost:3000/lab',
            data: {
                name: 'Lab 1',
                description: 'Lab 1 description'
            }
        }).then((response) => {
            console.log(response.data)
        });
    </script>
</body>
</html>

请求方式别名:

axios.get(url [,config])
axios.delete(url [,config])
axios.post(url [,data [,config]])
axios.put(url [,data [,config]])

AJAX - XMLHttpRequest 对象 (w3school.com.cn)

Axios中文文档 | Axios中文网 (axios-http.cn)


原文地址:https://blog.csdn.net/qq_63432403/article/details/142728468

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!