Skip to content

第 65 期(W3C 标准-JavaScript-异步):手写实现AJAX #68

@wingmeng

Description

@wingmeng

任务:
手写实现 AJAX

代码:

/**
 * @param {string} url - 请求的url地址
 * @param {string} method - 请求方式,get(默认) || post
 * @param {function} callback - 回调函数
 */
function sendAjaxRequest(url, method, callback) {
  var xhr = null;
  method = method || 'get';
  callback = typeof callback === 'function' ? callback : function() {};

  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveObject('Microsoft.XMLHTTP');  // 兼容低版本IE
  }

  xhr.open(method, url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        callback(data);
      }
    }
  }
  xhr.send(null);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions