ajax封装,promise封装ajax,axios封装

一、概念

ajax:

        核心XMLHttpRequest ,在不重新加载整个页面的情况下更新部分数据

promise:

        承诺,只有三种模式( pending:执行状态、fulfilled:已成功、rejected:已失败),且不受外界影响,解决回调地域

        官网地址:https://www.promisejs.org/

axios:

        基于promise的网络请求库

        参考地址:使用说明 · Axios 中文说明 · 看云

二、使用(封装)

1、ajax(原生封装)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>1121212</div>
  <script>
    //封装ajax请求
    function fun (options) {
      //初始化默认值
      options = options || {}
      options.type = (options.type || 'POST').toUpperCase()
      const params = options.data
      // 创建XMLHttpRequest对象
      const xhr = new XMLHttpRequest()
      //发送请求
      if (options.type === "GET") {
        xhr.open('GET', options.url + "?" + getParams(params), true)
        xhr.send()
      } else if (options.type === "POST") {
        xhr.open('POST', options.url, true)
        //设置请求头
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(getParams(params))

      }
      //设置返回信息格式
      xhr.responseType="json"
      //接收返回信息
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            options.success(xhr.response)
          } else {
            options.fail("参数错误" + status)
          }

        }
      }
    }
    //调用
    fun(
      {
        type: "post",
        url: 'http://192.168.166.146:8184/indexPage/readIndexPages',
        // url: ' http://192.168.166.146:8184/Topo/getCloudStatus',
        data: {
          name: 30
        },
        success: function (text, xml) { // 成功回调
          console.log(text, xml);
        },
        fail: function (status) { // 失败回调
          console.log(status);
        }
      }
    )
    //处理传值形式
    function getParams (data) {
      let arr = []
      for (const key in data) {
        arr.push(`${key}=${data[key]}`)
      }
      return arr.join('$')
    }
  </script>
</body>

</html>

2、promise封装ajax


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>1121212</div>
  <script>
    //封装ajax请求
    function fun (options) {
      return new Promise((resolve, reject) => {
        //初始化默认值
        options = options || {}
        options.type = (options.type || 'POST').toUpperCase()
        const params = options.data
        // 创建XMLHttpRequest对象
        const xhr = new XMLHttpRequest()
        //发送请求
        if (options.type === "GET") {
          xhr.open('GET', options.url + "?" + getParams(params), true)
          xhr.send()
        } else if (options.type === "POST") {
          xhr.open('POST', options.url, true)
          //设置请求头
          xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
          xhr.send(getParams(params))

        }
        //设置返回信息格式
        xhr.responseType = "json"
        //接收返回信息
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(xhr.response)
            } else {
              reject(new Error(xhr.statusText))
            }

          }
        }
        xhr.onerror = function () {
          reject(new Error(xhr.statusText))
        }
        //设置接口请求超时时间
        setTimeout(() => {
          //取消当前请求
          xhr.abort()
        }, 5000)

      })

    }
    //调用
    fun(
      {
        type: "post",
        url: 'http://192.168.166.146:8184/indexPage/readIndexPages',
        // url: ' http://192.168.166.146:8184/Topo/getCloudStatus',
        data: {
          name: 30
        },
      }
    ).then((res) => {
      console.log(res);
    }).catch((reson) => {
      console.log(reson);
    })
    //处理传值形式
    function getParams (data) {
      let arr = []
      for (const key in data) {
        arr.push(`${key}=${data[key]}`)
      }
      return arr.join('$')
    }
  </script>
</body>

</html>

3、axios(封装)

①、项目中src文件下创建utils文件,文件中创建request.js文件

import axios from 'axios'

export default request = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

②、项目中src文件下创建api文件,里面创建对应模块test.js文件

import request from '@/utils/request'
export function getAllData(params){
  return request({
    method:'GET',
    url:'/xxx',
    params,

  })
}

③、api文件中创建index.js文件,并且引入api文件下其他js文件

import test1 from './test1'
import test2 from './test2'
import test3 from './test3'

export default {
  test1,
  test2,
  test3,
}

④、挂载全局,在main.js文件中引入api文件下的index.js文件

import api from './api'

Vue.prototype.$api=api

⑤、引用

this.$api.test.getAllData()//传参数调用接口

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值