如何在 axios 中取消/中止 ajax 请求 [英] how to cancel/abort ajax request in axios

查看:64
本文介绍了如何在 axios 中取消/中止 ajax 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 axios 来处理 ajax 请求,使用 reactJS + flux 来渲染 UI.在我的应用程序中有第三侧时间线(reactJS 组件).时间轴可以通过鼠标滚动来管理.应用在任何滚动事件后发送对实际数据的 ajax 请求.服务器处理请求可能比下一个滚动事件更慢的问题.在这种情况下,应用程序可能有多个(通常为 2-3 个)请求,这些请求已经被弃用,因为用户进一步滚动.这是一个问题,因为每次接收新数据时,时间线都会开始重绘.(因为是reactJS+flux)正因为如此,用户看到时间轴来回移动了好几次.解决这个问题的最简单的方法,就是像 jQuery 一样中止之前的 ajax 请求.例如:

I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline can be managed by mouse's scroll. App sends ajax request for the actual data after any scroll event. Problem that processing of request at server can be more slow than next scroll event. In this case app can have several (2-3 usually) requests that already is deprecated because user scrolls further. it is a problem because every time at receiving of new data timeline begins redraw. (Because it's reactJS + flux) Because of this, the user sees the movement of the timeline back and forth several times. The easiest way to solve this problem, it just abort previous ajax request as in jQuery. For example:

    $(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

如何在axios中取消/中止请求?

How to cancel/abort requests in axios?

推荐答案

Axios 目前不支持取消请求.详情请参阅这个问题.

更新:取消支持已在 axios v0.15 中添加.

UPDATE: Cancellation support was added in axios v0.15.

axios 取消令牌 API 基于已撤销的可取消承诺提案.

The axios cancel token API is based on the withdrawn cancelable promises proposal.

示例:

const cancelTokenSource = axios.CancelToken.source();

axios.get('/user/12345', {
  cancelToken: cancelTokenSource.token
});

// Cancel request
cancelTokenSource.cancel();

这篇关于如何在 axios 中取消/中止 ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆