js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

使用Promise封装AJAX请求

Open Sunny-117 opened this issue 3 years ago • 7 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

function getJson(url){
    let promise = new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest()
        //创建一个http请求
        xhr.open('Get',url,true)
        xhr.onreadystatechange=function(){
            if(this.readyState!==4)return
            if(this.status>=200&&this.status<400){
                resolve(this.response)
            }else{
                reject(new Error(this.statusText))
            }     
        }
        //设置错误监听函数
        xhr.onerror=function(){
            reject(new Error(this.statusText))
        }
        //设置响应数据类型
        xhr.setRequestHeader('Accept',"application/json")
        //发送http请求
        xhr.send(null)
    })
    return promise
}

Coloey avatar Nov 22 '22 09:11 Coloey

function requestData(url, method, ...args) {
        return new Promise((res, rej) => {
          const xhr = new XMLHttpRequest();
          xhr.open(method, url);
          xhr.send();
          xhr.onload = () => {
            console.log(xhr);
            if (xhr.status !== 200) {
              console.log(11111);
              rej(new Error(`响应码${xhr.status}`));
            } else {
              res(xhr.response);
            }
          };
        });
      }
      requestData(url, "get")
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

hyxieshi avatar Jan 13 '23 15:01 hyxieshi

function myajax(url, method) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.send(null);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.response);
        } else {
          reject("error");
        }
      }
    };
  });
}

bearki99 avatar Feb 11 '23 12:02 bearki99

function asyncAjax(way, url, params) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();

    if (way === "get") {
      let param_list = [];
      for (let key of Object.keys(params)) {
        param_list.push(key + "=" + params[key]);
      }
      if (param_list.length !== 0) {
        let param_str = param_list.join("&");
        url += "?" + param_str;
      }

      xhr.open(way, url);
      xhr.send();
    } else {
      xhr.open(way, url);
      xhr.sendRequestHeader("Content-Type", "application/json");
      xhr.send(JSON.stringify(params))
    }

    xhr.onload = function(){
      if(this.status >= 200 && this.status <= 400) {
        resolve(this.response);
      }else {
        reject(new Error(this.statusText));
      }
    };

    xhr.onerror = function(){
      reject(this.statusText);
    }
  })
}

Erica-WX avatar Feb 15 '23 13:02 Erica-WX

function ajaxPromise(url, method, data) {
  return new Promise((resolve, reject) => {
    // 1.创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest();

    // 2.与服务器建立连接
    xhr.open(method, url, true);

    // 3.给服务器发送数据
    xhr.send(method === "POST" && data ? JSON.stringify(data) : null);

    // 4.接收请求
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 300) {
          resolve(JSON.parse(this.responseText));
        } else {
          reject(this.status);
        }
      }
    });
  });
}

ajaxPromise("GET", "https://dog.ceo/api/breeds/image/random")
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.error(err);
  });

xiaodye avatar Mar 18 '23 14:03 xiaodye

function axios(url, methods, ops) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); // 1. xhr.open(methods, url); // 设置请求头 xhr.setRequestHeader("a", 10); // 2. xhr.send({ b: 1 }); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.readyState === 200) { resolve(xhr.response); } else { reject("出问题了哦"); } } }; });

cscty avatar Jun 18 '23 15:06 cscty

function myAjax(url,options){
    const xhr = new XMLHttpRequest()
    return new Promise((resolve,reject) => {
        xhr.onload = function(...args){
            console.log(args)
            resolve()
        }
        xhr.onerror = function(...args){
            console.log(args)
            reject(new Error('请求失败'))
        }
        xhr.open(options.method,url)
        xhr.send(options.body)
    })
}

jianxingyao avatar Sep 15 '24 12:09 jianxingyao