Skip to content

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

Open

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);
}

Activity

  1. changed the title [-]第 65 期(W3C 标准-JavaScript-AJAX):手写实现AJAX[/-] [+]第 65 期(W3C 标准-JavaScript-异步):手写实现AJAX[/+] on Jul 21, 2019
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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions