request.ts 4.66 KB
import { AjaxParams } from 'request'
function ajax(params: AjaxParams): void {
  params = params || {}
  params.data = params.data || {}

  function json(params: AjaxParams): void {
    params.type = (params.type || 'GET').toUpperCase()
    params.data = formatParams(params.data)
    let xhr: XMLHttpRequest = new XMLHttpRequest()

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        const status = xhr.status
        if (status >= 200 && status < 300) {
          let response: any = ''
          const type = xhr.getResponseHeader('Content-type')!
          if (type.indexOf('xml') !== -1 && xhr.responseXML) {
            response = xhr.responseXML
          } else if (type === 'application/json') {
            response = JSON.parse(xhr.responseText)
          } else {
            response = xhr.responseText
          }
          params.success && params.success(response)
        } else {
          params.error && params.error(status)
        }
      }
    }

    if (params.type === 'GET') {
      xhr.open(params.type, params.url + '?' + params.data, true)
      xhr.send(null)
    } else {
      xhr.open(params.type, params.url, true)
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
      xhr.send(params.data)
    }
  }

  function formatParams(data: { [key: string]: any }): string {
    const arr: string[] = []
    for (const name in data) {
      arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]))
    }
    arr.push('v=' + random())
    return arr.join('&')
  }

  function random(): number {
    return Math.floor(Math.random() * 10000 + 500)
  }

  json(params)
}

class BeaconSend {
  public callback: (() => void) | null = null
  public server_url: string = ''

  start(data: any): void {
    if (!this.server_url) return
    if (typeof navigator === 'object' && typeof navigator.sendBeacon === 'function') {
      navigator.sendBeacon(this.server_url, data)
    }
    const _this = this
    setTimeout(function () {
      _this.end()
    }, 40)
  }

  end(): void {
    if (this.callback) {
      this.callback()
    }
  }
}

class ImageSend {
  public errorCallback: (() => void) | null = null
  public img: HTMLImageElement = document.createElement('img')
  public server_url: string = ''
  public datasend_timeout: number = 3000
  public ignore_oom: boolean = true
  public successCallBack: (() => void) | null = null

  constructor() {
    this.img.width = 1
    this.img.height = 1
    this.img.crossOrigin = 'anonymous'
  }

  start(): void {
    if (!this.server_url) return
    if (this.ignore_oom) {
      const _this = this
      this.img.onload = function () {
        this.onload = null
        this.onerror = null
        this.onabort = null
        if (_this.successCallBack) {
          _this.successCallBack()
        }
        _this.end()
      }
      this.img.onerror = function () {
        this.onload = null
        this.onerror = null
        this.onabort = null
        if (_this.errorCallback) {
          _this.errorCallback()
        }
        _this.end()
      }
      this.img.onabort = function () {
        this.onload = null
        this.onerror = null
        this.onabort = null
        if (_this.errorCallback) {
          _this.errorCallback()
        }
        _this.end()
      }
    }
    this.img.src = this.server_url
  }

  lastClear(): void {
    const sys = getUA()
    if (sys.ie !== undefined) {
      this.img.src = 'about:blank'
    } else {
      this.img.src = ''
    }
  }

  end(): void {
    const self = this
    setTimeout(function () {
      self.lastClear && self.lastClear()
    }, self.datasend_timeout)
  }
}
function getUA() {
  var Sys: any = {}
  var ua = navigator.userAgent.toLowerCase()
  var s
  if ((s = ua.match(/ qq\/([\d.]+)/))) {
    Sys.qqBuildinBrowser = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/mqqbrowser\/([\d.]+)/))) {
    Sys.qqBrowser = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/opera.([\d.]+)/))) {
    Sys.opera = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/msie ([\d.]+)/))) {
    Sys.ie = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/edge.([\d.]+)/))) {
    Sys.edge = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/firefox\/([\d.]+)/))) {
    Sys.firefox = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/chrome\/([\d.]+)/))) {
    Sys.chrome = Number(s[1].split('.')[0])
  } else if ((s = ua.match(/version\/([\d.]+).*safari/))) {
    Sys.safari = Number(s[1].match(/^\d*.\d*/))
  } else if ((s = ua.match(/trident\/([\d.]+)/))) {
    Sys.ie = 11
  }
  return Sys
}
let beason = new BeaconSend()
let imagehttp = new ImageSend()
const http = {
  beason,
  imagehttp,
  ajax
}
export default http