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


    一、概念

    ajax:

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

    promise:

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

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

    axios:

            基于promise的网络请求库

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

    二、使用(封装)

    1、ajax(原生封装)

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <div>1121212div>
    11. <script>
    12. //封装ajax请求
    13. function fun (options) {
    14. //初始化默认值
    15. options = options || {}
    16. options.type = (options.type || 'POST').toUpperCase()
    17. const params = options.data
    18. // 创建XMLHttpRequest对象
    19. const xhr = new XMLHttpRequest()
    20. //发送请求
    21. if (options.type === "GET") {
    22. xhr.open('GET', options.url + "?" + getParams(params), true)
    23. xhr.send()
    24. } else if (options.type === "POST") {
    25. xhr.open('POST', options.url, true)
    26. //设置请求头
    27. xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    28. xhr.send(getParams(params))
    29. }
    30. //设置返回信息格式
    31. xhr.responseType="json"
    32. //接收返回信息
    33. xhr.onreadystatechange = function () {
    34. if (xhr.readyState === 4) {
    35. if (xhr.status >= 200 && xhr.status < 300) {
    36. options.success(xhr.response)
    37. } else {
    38. options.fail("参数错误" + status)
    39. }
    40. }
    41. }
    42. }
    43. //调用
    44. fun(
    45. {
    46. type: "post",
    47. url: 'http://192.168.166.146:8184/indexPage/readIndexPages',
    48. // url: ' http://192.168.166.146:8184/Topo/getCloudStatus',
    49. data: {
    50. name: 30
    51. },
    52. success: function (text, xml) { // 成功回调
    53. console.log(text, xml);
    54. },
    55. fail: function (status) { // 失败回调
    56. console.log(status);
    57. }
    58. }
    59. )
    60. //处理传值形式
    61. function getParams (data) {
    62. let arr = []
    63. for (const key in data) {
    64. arr.push(`${key}=${data[key]}`)
    65. }
    66. return arr.join('$')
    67. }
    68. script>
    69. body>
    70. html>

    2、promise封装ajax

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <div>1121212div>
    11. <script>
    12. //封装ajax请求
    13. function fun (options) {
    14. return new Promise((resolve, reject) => {
    15. //初始化默认值
    16. options = options || {}
    17. options.type = (options.type || 'POST').toUpperCase()
    18. const params = options.data
    19. // 创建XMLHttpRequest对象
    20. const xhr = new XMLHttpRequest()
    21. //发送请求
    22. if (options.type === "GET") {
    23. xhr.open('GET', options.url + "?" + getParams(params), true)
    24. xhr.send()
    25. } else if (options.type === "POST") {
    26. xhr.open('POST', options.url, true)
    27. //设置请求头
    28. xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    29. xhr.send(getParams(params))
    30. }
    31. //设置返回信息格式
    32. xhr.responseType = "json"
    33. //接收返回信息
    34. xhr.onreadystatechange = function () {
    35. if (xhr.readyState === 4) {
    36. if (xhr.status >= 200 && xhr.status < 300) {
    37. resolve(xhr.response)
    38. } else {
    39. reject(new Error(xhr.statusText))
    40. }
    41. }
    42. }
    43. xhr.onerror = function () {
    44. reject(new Error(xhr.statusText))
    45. }
    46. //设置接口请求超时时间
    47. setTimeout(() => {
    48. //取消当前请求
    49. xhr.abort()
    50. }, 5000)
    51. })
    52. }
    53. //调用
    54. fun(
    55. {
    56. type: "post",
    57. url: 'http://192.168.166.146:8184/indexPage/readIndexPages',
    58. // url: ' http://192.168.166.146:8184/Topo/getCloudStatus',
    59. data: {
    60. name: 30
    61. },
    62. }
    63. ).then((res) => {
    64. console.log(res);
    65. }).catch((reson) => {
    66. console.log(reson);
    67. })
    68. //处理传值形式
    69. function getParams (data) {
    70. let arr = []
    71. for (const key in data) {
    72. arr.push(`${key}=${data[key]}`)
    73. }
    74. return arr.join('$')
    75. }
    76. script>
    77. body>
    78. html>

    3、axios(封装)

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

    1. import axios from 'axios'
    2. export default request = axios.create({
    3. baseURL: 'https://some-domain.com/api/',
    4. timeout: 1000,
    5. headers: {'X-Custom-Header': 'foobar'}
    6. });

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

    1. import request from '@/utils/request'
    2. export function getAllData(params){
    3. return request({
    4. method:'GET',
    5. url:'/xxx',
    6. params,
    7. })
    8. }

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

    1. import test1 from './test1'
    2. import test2 from './test2'
    3. import test3 from './test3'
    4. export default {
    5. test1,
    6. test2,
    7. test3,
    8. }

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

    1. import api from './api'
    2. Vue.prototype.$api=api

    ⑤、引用

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

  • 相关阅读:
    easyPoster一个基于uniapp的canvas绘制海报库支持绘制图表到海报中
    mysql docker 安装
    还在想消除笔怎么用?这有几个易操作的软件
    【华为OD机试真题 python】 拼接url【2022 Q4 | 100分】
    《Python+Kivy(App开发)从入门到实践》自学笔记:第六章 打包——知识点总览
    HZOJ-838:2020年数据结构41题
    [nlp] 对抗学习 FGM, PGD到FreeLB
    unity操作_光源组件 c#
    C++学习之路-智能指针
    get与post的区别
  • 原文地址:https://blog.csdn.net/flhhly/article/details/126785866