Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用Promise封装AJAX请求 #154

Open
Sunny-117 opened this issue Nov 3, 2022 · 6 comments
Open

使用Promise封装AJAX请求 #154

Sunny-117 opened this issue Nov 3, 2022 · 6 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Coloey
Copy link

Coloey commented Nov 22, 2022

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
}

@hyxieshi
Copy link

hyxieshi commented Jan 13, 2023

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);
        });

@bearki99
Copy link

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");
        }
      }
    };
  });
}

@Erica-WX
Copy link

Erica-WX commented Feb 15, 2023

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);
    }
  })
}

@xiaodye
Copy link

xiaodye commented Mar 18, 2023

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);
  });

@cscty
Copy link

cscty commented Jun 18, 2023

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("出问题了哦");
}
}
};
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants