zoukankan      html  css  js  c++  java
  • axios的封装

    function axios(options){
        var promise = new Promise((resolve,reject)=>{
            var xhr = null;
            if(window.XMLHttpRequest){
                xhr = new XMLHttpRequest();
            }else{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var str = "";
            //进行传入数据的处理
            for(var key in options.data){
                str += "&" + key + "=" + options.data[key];
            }
            if(options.method == "get"){
                var url = options.url + "?" + data.slice(1);//因为在前面将传入的数据多加了一个&符号,然而需要的是&之后的数据
                xhr.open(options.method,url);
                xhr.send();//通过get方式请求数据不需要发送数据
            }else if(options.method == "post"){
                xhr.open(options.method,options.url);
                xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
                xhr.send(str);
            }
            xhr.onreadystatechange = function(){
                var timer = null;
                //timeout是ajax请求中的一个默认属性,表示时间。如果该默认属性存在则使用默认值,否则使用5000毫秒
                var timeout = options.timeout?options.timeout:5000;
                if(xhr.readState == 4 && xhr.status == 200){
                    var res = JSON.parse(xhr.responseText);
                    clearTimeout(timer);
                    resolve(res);
                }
                timer = setTimeout(()=>{
                    clearTimeout(timer);
                    reject(xhr.status);
                },timeout);
            }
        })
        return promise;
    }
  • 相关阅读:
    同一台Windows机器中启动多个Memcached服务
    Java注解(三)
    Java注解(二)
    Java注解(一)
    Memcached入门
    C++读取配置文件
    C语言读取配置文件
    凸优化中的基本概念
    Hadoop伪分布式的搭建
    老师布置的几道作业
  • 原文地址:https://www.cnblogs.com/Leslie-Cheung1584304774/p/10576763.html
Copyright © 2011-2022 走看看