美文网首页Ajax
简易封装XMLHttpRequest

简易封装XMLHttpRequest

作者: Armin0202 | 来源:发表于2017-11-30 09:36 被阅读301次

    场景

    • 一些小小的 js 文件,需要用到 http request。例如:封装微信分享的 js 文件
    • 引入库,太大了。还不如自己简单封装一个
    • 仅仅简单的 'GET'、'POST'方法,简单的数据数据请求

    方案策略


    方案代码

    function request(option) {
      if (String(option) !== '[object Object]') return undefined
      option.method = option.method ? option.method.toUpperCase() : 'GET'
      option.data = option.data || {}
      var formData = []
      for (var key in option.data) {
        formData.push(''.concat(key, '=', option.data[key]))
      }
      option.data = formData.join('&')
    
      if (option.method === 'GET') {
        option.url += location.search.length === 0 ? ''.concat('?', option.data) : ''.concat('&', option.data)
      }
    
      var xhr = new XMLHttpRequest()
      xhr.responseType = option.responseType || 'json'
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            if (option.success && typeof option.success === 'function') {
              option.success(xhr.response)
            }
          } else {
            if (option.error && typeof option.error === 'function') {
              option.error()
            }
          }
        }
      }
      xhr.open(option.method, option.url, true)
      if (option.method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      }
      xhr.send(option.method === 'POST' ? option.data : null)
    }
    

    调用方法:

    request({
        url: 'api',
        method: 'POST',
        data: {},
        success: function (res) {
    
        },
        error: function (err) {
    
        }
    })
    

    相关文章

      网友评论

        本文标题:简易封装XMLHttpRequest

        本文链接:https://www.haomeiwen.com/subject/fowmbxtx.html