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 #208

Open
louzhedong opened this issue Mar 17, 2020 · 2 comments
Open

手写AJAX #208

louzhedong opened this issue Mar 17, 2020 · 2 comments

Comments

@louzhedong
Copy link
Owner

louzhedong commented Mar 17, 2020

使用原生的XMLHttpRequest实现一个ajax

/**

- 
- @param {*} options 
- url
- data
- method
- async
- timeout
*/
function ajax(options) {
  let url = options.url;
  const method = options.method.toLocaleLowerCase() || 'get';
  const async = options.async != false;  // default is true
  const data = options.data;

  const xhr = new XMLHttpRequest();

  if (options.timeout && options.timeout > 0) {
    xhr.timeout = options.timeout;
  }

  return new Promise((resolve, reject) => {
    xhr.ontimeout = () => {reject && reject('请求超时');}
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) { // 请求完成
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
          resolve && resolve(xhr.responseText);
        } else {
          reject && reject();
        }
      }
    }
    xhr.onerror = err => reject && reject(err);

    let paramList = [];
    let encodeData;
    if (data instanceof Object) {
      for (let key in data) {
        paramList.push(encodeURIComponent(key)   '='   encodeURIComponent(data[key]));
      }
      encodeData = paramList.join('&');
    }
    
    if (method === 'get') {
      const index = url.indexOf('?');
      if (index === -1) {
        url  = '?';
      } else if (index !== url.length - 1) {
        url  = '&';
      }
      url  = encodeData;
    }
    
    xhr.open(method, url, async);
    if (method === 'get') {
      xhr.send(null);
    } else {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
      xhr.send(encodeData);
    }

  })
}
@axnir
Copy link

axnir commented Nov 16, 2020

options.method.toLocalLowerCase()少了一个字母,toLocaleLowerCase()

@louzhedong
Copy link
Owner Author

options.method.toLocalLowerCase()少了一个字母,toLocaleLowerCase()

thanks

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

2 participants