zoukankan      html  css  js  c++  java
  • promise封装ajax

    const axios = function(options){
        let promise = new promise(( resolve , reject )=>{
            var xhr = null;
            if(window.XMLHttpRequest){//兼容处理
               xhr = new XMLHttpRequest();
           }else{
               xhr = new ActiveXObject("Microsoft.XMLHTTP");   
           }
             var data = "";
            for (var key in options.data) {//数据处理
                data += "&" + key + "=" + options.data[key]
            }
           if (options.method == "get") {
    
                let url = options.url + "?" + data.slice(1);
                xhr.open(options.method, url);
                xhr.send();
            } else if (options.method == "post") {
    
                xhr.open(options.method, options.url);
                xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
                xhr.send(data);
            }
    
        
            xhr.onreadystatechange = function () {
                let timer = null;
                let timeout = options.timeout?options.timeout:5000  //等待响应的时间 
                if(xhr.readyState == 4 && xhr.status == 200){
                    let res = JSON.parse(xhr.responseText);
                    clearTimeout(timer);
                    resolve(res);
                }
                 
    
                timer = setTimeout(()=>{
                    clearTimeout(timer);
                    reject(xhr.status);
                },timeout) 
                
            }
        })
        return promise;
    }    

    栗子:

     axios({
            method:"get",
            url:"./data.json",
            data:{
                id:10
            }
        }).then((res)=>{
            console.log(res)
        },(e)=>{
            console.log(e);
        })
  • 相关阅读:
    HDU5620 KK's Steel(C++语言版)
    HDU5620 KK's Steel(C语言版)
    大整数分解算法
    大整数分解算法
    HDU1319 POJ1595 UVA406 UVALive5490 ZOJ1312 Prime Cuts【素数筛选+打表】
    HDU1106 排序
    B00004 atoi函数
    B00004 atoi函数
    HDU1262 寻找素数对
    HDU1262 寻找素数对
  • 原文地址:https://www.cnblogs.com/wildccy/p/10543154.html
Copyright © 2011-2022 走看看