基于原生 XMLHttpRequest 封装 get 方法

314 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

XMLHttpRequest 对象用于在后台与服务器交换数据。做web开发,我们都知道浏览器通过XMLHttpRequest对象进行http通信,在实际开发中我们使用的是各种框架封装了的XMLHttpRequest对象,对具体实现往往一知半解。下面通过一个简单里学习一下XMLHttpRequest的原理。

构造函数

  • XMLHttpRequest()

该构造函数用于初始化一个 XMLHttpRequest 实例对象。在调用下列任何其他方法之前,必须先调用该构造函数,或通过其他方式,得到一个实例对象。

  • 创建 XMLHttpRequest 对象的语法:

xmlhttp=new XMLHttpRequest();

let xhr = new XMLHttpRequest();
// 请求成功回调函数
xhr.onload = e => {
    console.log('请求成功');
};
// 请求结束时的回调函数
xhr.onloadend = e => {
    console.log('请求结束');
};
// 请求出错时的回调函数
xhr.onerror = e => {
    console.log('请求出错');
};
// 请求超时时的回调函数
xhr.ontimeout = e => {
    console.log('请求超时');
};

xhr.timeout = 0; // 设置超时时间,0表示永不超时
// 初始化请求
xhr.open('GET/POST/DELETE/...', '/url', true || false);
// 设置期望的返回数据类型 'json' 'text' 'document' ...
xhr.responseType = '';
// 设置请求头
xhr.setRequestHeader('', '');
// 发送请求
xhr.send(null || new FormData || 'a=1&b=2' || 'json字符串');

1、写一个 json 文件 data.json

{
    {
      "id": 1,
      "username": "tiantian",
      "age": 23,
    },
    {
      "id": 2,
      "username": "lzp",
      "age": 28,
    },
    {
      "id": 3,
      "username": "nn",
      "age": 28,
    },
    {
      "id": 4,
      "username": "few",
      "age": 18,
    },
    {
      "id": 5,
      "username": "5566",
      "age": 22,
    }
}

2、方法封装

function get(url, callback) {
      var oReq = new XMLHttpRequest()
      // 当请求加载成功之后要调用指定的函数
      oReq.onload = function () {
        // 我现在需要得到这里的 oReq.responseText
        callback(oReq.responseText)
      }
      oReq.open("get", url, true)
      oReq.send()
    }

    get('data.json', function (data) {
      console.log(data)
    })