Ajax、Axios和Fetch的用法和区别,撤回请求,防抖节流,针对处理高频率请求的场景如何处理?

在现代JavaScript开发中,用于进行HTTP请求的三种主要方式是Ajax、Axios和Fetch。这三种方式各有优缺点,并且适用于不同的场景。在合适的业务场景下使用,以下是它们的区别和使用举例。并且实现撤回或取消请求,减少不必要的重复请求,在同时有高频率大量请求时,放入请求队列,以及前端的防抖或者节流,提高前端性能优化。

1. Ajax

Ajax(Asynchronous JavaScript and XML)是一种使用JavaScript和XML进行异步网页更新的技术。尽管其名称中包含XML,但它可以处理多种数据格式,包括JSON、HTML和纯文本。传统上,Ajax使用的是XMLHttpRequest对象。

Ajax 示例

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Example</title>
</head>
<body>
    <button id="loadData">Load Data</button>
    <div id="result"></div>

    <script>
        document.getElementById('loadData').addEventListener('click', function() {
     
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
            xhr.onreadystatechange = function () {
     
                if (xhr.readyState === 4 && xhr.status === 200) {
     
                    document.getElementById('result').innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        });
    </script>
</body>
</html>

2. Axios

Axios是一个基于Promise的HTTP库,可以用于浏览器和Node.js。它具有简单易用的API,支持拦截请求和响应、取消请求、自动转换JSON数据等功能。

安装 Axios

在使用Axios之前,需要安装它:

npm install axios

Axios 示例

<!DOCTYPE html>
<html>
<head>
    <title>Axios Example</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <button id="loadData">Load Data</button>
    <div id="result"></div>

    <script>
        document.getElementById('loadData').addEventListener('click', function() {
     
            axios.get('https://jsonplaceholder.typicode.com/posts/1')
                .then(function(response) {
     
                    document.getElementById('result').innerHTML = JSON.stringify(response.data, null, 2);
                })
                .catch(function(error) {
     
                    console.error('Error:', error);
                });
        });
    </script>
</body>
</html>

3. Fetch

Fetch API是现代浏览器中用来替代XMLHttpRequest的,提供了一个更强大和灵活的方式来发起网络请求。它基于Promise,语法更加简洁。

Fetch 示例

<!DOCTYPE html>
<html>
<head>
    <title>Fetch Example</title>
</head>
<body>
    <button id="loadData">Load Data</button>
    <div id="result"></div>

    <script>
        document.getElementById('loadData').addEventListener('click', function() {
     
            fetch('https://jsonplaceholder.typicode.com/posts/1')
                .then(response => response.json())
                .then(data => {
     
                    document.getElementById('result').innerHTML = JSON.stringify(data, null, 2);
                })
                .catch(error => {
     
                    console.error('Error:', error);
                });
        });
    </script>
</body>
</html>

区别与比较

  1. 使用简便性

    • Ajax:使用XMLHttpRequest对象,需要处理各种状态和事件,代码较为冗长。
    • Axios:基于Promise,API设计更简洁,使用更方便,支持更多功能。
    • Fetch:原生Promise支持,语法简洁,但需要处理一些低级错误(例如网络错误不会被捕捉到,需要手动处理response.ok)。
  2. 浏览器支持

    • Ajax:所有现代浏览器都支持。
    • Axios:需要引入外部库,但支持所有现代浏览器。
    • Fetch:所有现代浏览器(Edge开始支持),但对于老版本浏览器(如IE)需要使用polyfill。
  3. 功能特性

    • Ajax:功能较为基础,需要手动处理各种请求和响应。
    • Axios:支持请求和响应拦截器、自动转换JSON数据、取消请求等高级功能。
    • Fetch:提供基本功能,响应处理需要手动转换(例如JSON),且不支持progress事件和取消请求。

撤回或者取消请求,实现请求的防抖节流

在前端开发中,撤回或取消HTTP请求,防抖和节流都是优化网络请求和提升用户体验的重要技术。以下是详细的解释和实现方法。

1. 撤回或取消HTTP请求

Axios

Axios 提供了取消请求的功能,通过使用 CancelToken

取消请求示例
<!DOCTYPE html>
<html>
<head>
    <title>Axios Cancel Request Example</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <button id="startRequest">Start Request</button>
    <button id="cancelRequest">Cancel Request</button>
    <div id="result"></div>

    <script>
        let cancelTokenSource;

        document.getElementById('startRequest').addEventListener('click', function() {
     
            cancelTokenSource = axios.CancelToken.source();

            axios.get('https://jsonplaceholder.typicode.com/posts/1', {
     
                cancelToken: cancelTokenSource.token
            })
            .then(function(response) {
     
                document.getElementById('result').innerHTML = JSON.stringify(response.data, null, 2);
            })
            .catch(function(error) {
     
                if (axios.isCancel(error)) {
     
                    console.log('Request canceled', error.message);
                } else {
     
                    console.error('Error:', error);
                }
            });
        });

        document.getElementById('cancelRequest').addEventListener('click', function() {
     
            if (cancelTokenSource) {
     
                cancelTokenSource.cancel('Request canceled by the user.');
            }
        });
    </script>
</body>
</html>

Fetch

Fetch API 原生不支持取消请求,但可以通过 AbortController 来实现。

取消请求示例
<!DOCTYPE html>
<html>
<head></
  • 18
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为了WLB努力

给点小钱,你的鼓励是我坚持动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值