vue ajax 请求封装,实现类似jquery的ajax请求效果(可配置同步、异步请求)

1、封装函数

/**
 * XMLHttpRequest 简单封装
 * @param option
 * @return {undefined}
 */
export function ajaxRequest (option) {
  // 1. 首先简单验证传进来的参数是否合法
  // if (Object.prototype.toString.call(option) !== '[object, Object]') return undefined
  // 2. 对参数容错处理
  option.method = option.method ? option.method.toUpperCase() : 'GET' // 默认 GET 请求
  option.data = option.data || {}
  option.type = option.type || 'json'

  // 3. 如果是 GET 请求,需要处理 data 里的数据并且以一定的规则拼接到 url 后
  if (option.method === 'GET') {
    var formData = []
    for (let key in option.data) { // Object.keys.forEach
      formData.push(''.concat(key, '=', option.data[key]))
    }
    option.data = formData.join('&') // eg: a=b&c=d&e=f
    if (option.method === 'GET' && formData.length > 0) { // 注意,option.data 为空对象的时候,就不用拼接参数了
      // 连接本身有参数的时候拼接 &option.data,如果本身没有参数拼接 ?option.data
      option.url += location.search.length === 0 ? ''.concat('?', option.data) : ''.concat('&', option.data)
    }
  }
  // 4. 实例化 XMLHttpRequest 对象,并进行一些设置
  var xhr = new XMLHttpRequest()
  xhr.onload = 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(new Error(xhr.statusText))
        }
      }
    }
  }
  xhr.open(option.method, option.url, option.async) // true 代表是异步请求
  // 6. 如果是 POST 请求,需要设置请求头
  if (option.method === 'POST') {
    // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  }
  // 7. 发送请求
  xhr.send(option.method === 'POST' ? option.data : null)
}

2、函数调用

import { ajaxRequest } from '@/utils/utils'
......
ajaxRequest(
{
  url: url,
  method: 'GET',
  type: 'json',
  data: {},
  async: false,
  success: function (res) {
    let features = JSON.parse(res).features
    if (features.length > 0) {
      resinfo = features[0]
    }
  },
  error: function () {
    resinfo = null
  }
})
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gis分享者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值