Skip to content

手写AJAX #208

Open
Open

Description

@louzhedong

使用原生的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);
    }

  })
}

Activity

  1. axnir commented on Nov 16, 2020

    @axnir

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

  2. louzhedong commented on Nov 16, 2020

    @louzhedong
    OwnerAuthor

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

    thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions