原生ajax的get方法封装

get 方法:

    function serialize (data) {
      if (!data) {
        return '';
      }
      
      var paris = [];
      for (var key in data) {
        if (!data.hasOwnProperty(key) || typeof data[key] === 'function') {
          continue;
        }
        var name = encodeURIComponent(key);
        var value = encodeURIComponent(data[key].toString());
        paris.push(name + '=' + value);
      }
      return paris.join('&');
    }

    function get (url, options, callback) {
      var req;
      if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
      } else if (window.ActiveXObject) { // 兼容IE7及以下版本
        req = new ActiveXObject();
      }
      
      req.onreadystatechange = function () {
        if (req.readyState === 4) {
          if (req.status === 200) {
            console.log('请求成功');
            callback(req.response);
          }
        } else {
          console.log('请求中...');
        }
      }
      
      // 将传递的参数序列化
      if (serialize(options) !== '') {
        url = url + '?' + serialize(options);
      }

      req.open('get', url);
      req.send();
    }

猜你喜欢

转载自www.cnblogs.com/qiuxiaozhen/p/10568314.html