Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

任务:
手写实现 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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.