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

封装ajax函数 && 实现一个axios #26

Open
mtonhuang opened this issue Dec 11, 2020 · 0 comments
Open

封装ajax函数 && 实现一个axios #26

mtonhuang opened this issue Dec 11, 2020 · 0 comments

Comments

@mtonhuang
Copy link
Owner

mtonhuang commented Dec 11, 2020

基础——XHR用法

    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        //xhr.readyState == 4时,表示所有数据已经准备就绪
        if (xhr.readyState == 4) {
             //status 为200时表示成功,304则表示资源没有被修改,继续使用缓存
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                console.log(xhr.responseText)
            } else {
                console.log(xhr.status)
            }
        }
    };
    xhr.open('get', 'test.txt', true);
    xhr.send(null)

基于原生js封装简易的ajax函数

    let ejax = {
      get: function(url, fn, async) {
        let xhr = new XMLHttpRequest();
        xhr.open(url, "GET");
        xhr.onreadystatechange = () => {
          if ((xhr.readyState == 4 && xhr.status == 200) || xhr.status == 304) {
            let result = xhr.responseText;
            fn.call(this, result);
          }
        };
        xhr.send();
      },
      post: function(url, fn, async) {
        let xhr = new XMLHttpRequest();
        xhr.open(url, "POST", async);
        xhr.setRequestHeader(
          "conten-type",
          "application/x-www-form-urlencoded"
        );
        xhr.onreadystatechange = () => {
          if (
            (xhr.readyState === 4 && xhr.status == 200) ||
            xhr.status == 304
          ) {
            let result = xhr.responseText;
            fn.call(this, result);
          }
        };
        xhr.send(data);
      }
    };

基于Promise实现一个简易的axios

    let exios = function({
      url = null,
      method = "GET",
      dataType = "JSON",
      async = true,
    }) {
      let promiseApi = new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(method, url, async);
        xhr.responseType = dataType;
        xhr.onreadystatechange = () => {
          if (!/^[23]\d{2}$/.test(xhr.status)) return;
          if (xhr.readyState === 4) {
            let result = xhr.responseText;
            resolve(result);
          }
        };
        xhr.onerror = (err) => {
          reject(err);
        };
        xhr.send();
      });
      return promiseApi;
    };
  }
@mtonhuang mtonhuang changed the title 基于原生js封装ajax函数 && 基于Promise实现一个axios 封装ajax函数 && 实现一个axios Dec 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant