zoukankan      html  css  js  c++  java
  • Js取消异步请求

    1.xhr:对于原生XHR对象来说,取消的ajax的关键是调用XHR对象的.abort()方法

        var xhr = new XMLHttpRequest();
        xhr.open("GET","https://api.github.com/");
        xhr.send();
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                console.log(xhr.response);
            }else{
                console.log(xhr.status);
            }
        }
        xhr.abort();
    

    2.jQuery:jQuery为我们封装了ajax请求接口,在jQuery中,取消ajax请求也是通过调用.abort()方法,只不过操作的对象不再是原生XHR对象

       var jq = $.ajax({
            type:"get",
            url:"https://api.github.com/",
            dataType:"json",
            success:function(data){
                console.log(data);
            },
            error:function(err){
                console.log(err);
            }
        })
        jq.abort();
    

    3.axios:经常使用vue等框架的话,就会使用axios发送ajax请求。在axios中取消ajax请求不同于上面两种形式,在axios中是通过axios.CancelToken.source()方法取消请求

        var CancelToken = axios.CancelToken;
        var source = CancelToken.source();
    
        axios({
            method:"GET",
            url:"https://api.github.com/",
            cancelToken:source.token
            //cancelToken的值起标识作用,标识由source控制的、将要被取消的ajax操作
        }).then((res) => {
            console.log(res.data);
        }).catch((err) => {
            console.log(err);
        });
    
        source.cancel('Operation canceled by the user.');
    

      如果我们有多个通过axios发送的ajax请求,需要精准的取消掉指定的请求应该这么做呢?在上面的代码中有注释“cancelToken的值起标识作用,标识由source控制的、将要被取消的ajax操作

    var CancelToken = axios.CancelToken;
    
    var source = CancelToken.source();
    axios({
        method:"GET",
        url:"https://api.github.com/",
        cancelToken:source.token
    }).then((res) => {
        console.log(res.data);
    }).catch((err) => {
        console.log(err);
    });
    
    var custom = CancelToken.source();
    axios({
        method:"GET",
        url:"https://api.github.com/",
        cancelToken:custom.token
    }).then((res)=>{
        console.log(res.data);
    }).catch((err)=>{
        console.log(err);
    });
    
    source.cancel('Operation canceled by the user.');
    custom.cancel('精确取消');
    

     综上三种方式

  • 相关阅读:
    Windows Server 2012配置开机启动项
    Windows Server 2019 SSH Server
    NOIP2017 senior A 模拟赛 7.7 T1 棋盘
    Noip 2015 senior 复赛 Day2 子串
    Noip 2015 senior复赛 题解
    Noip 2014 senior Day2 解方程(equation)
    Noip 2014 senior Day2 寻找道路(road)
    Noip 2014 senior Day2 无线网络发射器选址(wireless)
    Noip2014senior复赛 飞扬的小鸟
    Noip 2014 senior 复赛 联合权值(link)
  • 原文地址:https://www.cnblogs.com/yxkNotes/p/13931706.html
Copyright © 2011-2022 走看看