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

使用场景

检查接口可用性

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

验证接口用于爬虫

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

减少依赖

因为可以直接使用原生 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);

发送GET请求

完整版:

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) {
	// 这里对结果进行处理
});

参考链接:

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值