最简单的方式使用原生 js 发送 http 请求

#编程技术 2020-09-21 20:20:17 | 全文 608 字,阅读约需 2 分钟 | 加载中... 次浏览

👋 相关阅读


使用场景

1、检查接口可用性

主要用于在没有引入 jQuery 等工具的页面上需要验证一些 api 能否调得通的时候,可以快速调出浏览器调试界面发请求。 这在判断是否存在跨域问题的场景下,特别好用。

2、验证接口用于爬虫

另外,因为在浏览器调试界面发起的请求跟页面自身的 js 发起的请求是一样的,所以可以不用关心登录状态等上下文环境的问题。这在写爬虫的时候特别实用——抓到一个链接之后,直接在浏览器上进行验证,先调用一下试试好不好用再说。

3、减少依赖 因为可以直接使用原生 js,因此无需添加 jQuery、axios 等第三方工具就可以发送 http 就请求,可以减少应用的体积。

实现

简易版

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if( xhr.readyState == 4){
         if( xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
             info.innerHTML = xhr.responseText;
          }
     }
};

// 每次需要发请求需要做两步:
xhr.open("get", url, true);
xhr.send(null);

完整版:

var http = {};
http.quest = function (option, callback) {
  var url = option.url;
  var method = option.method;
  var data = option.data;
  var timeout = option.timeout || 0;
  var xhr = new XMLHttpRequest();
  (timeout > 0) && (xhr.timeout = timeout);
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status >= 200 && xhr.status < 400) {
        var result = xhr.responseText;
        try { result = JSON.parse(xhr.responseText); } catch (e) { }
        callback && callback(null, result);
      } else {
        callback && callback('status: ' + xhr.status);
      }
    }
  }.bind(this);
  xhr.open(method, url, true);
  if (typeof data === 'object') {
    try {
      data = JSON.stringify(data);
    } catch (e) { }
  }
  xhr.send(data);
  xhr.ontimeout = function () {
    callback && callback('timeout');
    console.log('%c连%c接%c超%c时', 'color:red', 'color:orange', 'color:purple', 'color:green');
  };
};
http.get = function (url, callback) {
  var option = url.url ? url : { url: url };
  option.method = 'get';
  this.quest(option, callback);
};
http.post = function (option, callback) {
  option.method = 'post';
  this.quest(option, callback);
};

//普通get请求
http.get('http://www.baidu.com', function (err, result) {
	// 这里对结果进行处理
});

//定义超时时间(单位毫秒)
http.get({ url: 'http://www.baidu.com', timeout: 1000 }, function (err, result) {
	// 这里对结果进行处理
});

//post请求
http.post({ url: 'http://www.baidu.com', data: '123', timeout: 1000 }, function (err, result) {
	// 这里对结果进行处理
});

via: https://blog.csdn.net/dadiyang/article/details/93383443

Edit | Last updated on 2024-04-21 11:10:27




×