当前位置: 首页 > article >正文

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)


http://www.kler.cn/news/336068.html

相关文章:

  • Spring Boot:医院管理的数字化转型
  • 【Python】PDFMiner.six:高效处理PDF文档的Python工具
  • 【redis-05】redis保证和mysql数据一致性
  • 解决Python使用Selenium 时遇到网页 <body> 划不动的问题
  • C语言 | Leetcode C语言题解之第457题环形数组是否存在循环
  • 排查和解决JVM OOM实战
  • 视频美颜SDK与直播美颜工具API的架构设计与实现
  • IDEA中配置启动类的Active Profiles
  • 网络资源模板--Android Studio 停车场管理系统
  • 基于深度学习的视频内容理解
  • 【移动端】事件基础
  • 什么是区块链桥?
  • 系统设计,如何设计一个秒杀功能
  • SpringBoot基础(四):bean的多种加载方式
  • 【Redis】持久化(上)---RDB
  • 【AI知识点】如何对包含异常值的数据进行归一化处理?
  • 使用 Python 实现无人机避障的人工势场算法
  • 简洁之道 - React Hook Form
  • 0108 Spring Boot启动过程
  • wsl中git difftool調用beyond compare