• js Ajax函数封装及使用


    直接上代码

    一、ajax函数封装
    1. /**
    2. * ajax函数
    3. * @param {Object} options 请求传入的对象参数
    4. */
    5. function ajax(options = {}) {
    6. // 1. 参数校验
    7. // 校验请求地址必传,而只能是字符串类型
    8. if (!options.url || typeof (options.url) != 'string') throw Error('url必传,只能是字符串');
    9. // 校验请求方式 只能是post或get 或者不传递
    10. if (!(typeof options.method === 'undefined' || /^(get|post)$/i.test(options.method))) throw Error('method只能是post或get');
    11. // 校验请求方式 只能是post或get 或者不传递
    12. if (!(typeof options.dataType === 'undefined' || /^(string|json)$/i.test(options.dataType))) throw Error('dataType只能是json或string');
    13. // 校验携带的参数 只能是对象 或者不传递
    14. if (!(typeof options.data === 'undefined' || Object.prototype.toString.call(options.data) === '[object Object]')) throw Error('data只能是对象');
    15. // 校验请求是否异步 只能是布尔类型 或者不传递
    16. if (!(typeof options.async === 'undefined' || typeof options.async === 'boolean')) throw Error('async只能是布尔值');
    17. // 校验请求头 只能是对象 或者不传递
    18. if (!(typeof options.header === 'undefined' || Object.prototype.toString.call(options.header) === '[object Object]')) throw Error('header只能是对象');
    19. // 校验成功函数 只能是函数 或者不传递
    20. if (!(typeof options.success === 'undefined' || typeof options.success === 'function')) throw Error('success只能是函数');
    21. // 校验错误函数 只能是函数 或者不传递
    22. if (!(typeof options.error === 'undefined' || typeof options.error === 'function')) throw Error('error只能是函数');
    23. // console.log( options )
    24. // 2. 准备ajax请求的默认值
    25. let defInfo = {
    26. url: options.url,
    27. method: options.method ? options.method : 'get',
    28. data: options.data ? options.data : {},
    29. dataType: options.dataType ? options.dataType : 'string',
    30. async: typeof options.async==='boolean'?options.async:true,
    31. //?? 空值合并运算符 当左侧的操作数为null 或者undefined 时,返回其右侧操作数,否则返回左侧操作数。
    32. //async: options.async ?? true,
    33. header: { 'content-type': 'application/x-www-form-urlencoded', ...options.header },
    34. success: options.success ? options.success : () => { },
    35. error: options.error ? options.error : () => { },
    36. }
    37. // console.log( defInfo )
    38. // 3. 组装查询字符串
    39. let queryStr = '';
    40. // 遍历defInfo.data
    41. for (const key in defInfo.data) {
    42. queryStr += `${key}=${defInfo.data[key]}&`;
    43. }
    44. queryStr = queryStr.slice(0, -1);
    45. // 判断是否将查询字符串拼接到 地址中
    46. if (/get/i.test(defInfo.method)) defInfo.url += `?${queryStr}`;
    47. // 创建ajax对象
    48. let xhr = new XMLHttpRequest();
    49. // 配置请求信息
    50. xhr.open(defInfo.method, defInfo.url, defInfo.async);
    51. // 设置请求头
    52. for (const key in defInfo.header) {
    53. xhr.setRequestHeader(key, defInfo.header[key])
    54. }
    55. // 发送请求
    56. /post/i.test(defInfo.method) ? xhr.send(queryStr) : xhr.send();
    57. // 接受响应
    58. xhr.onload = function () {
    59. let res = xhr.responseText;
    60. try {
    61. // 判断是否需要json转换
    62. if (defInfo.dataType === 'json') {
    63. res = JSON.parse(res);
    64. }
    65. // 执行成功回调---将接受的响应数据作为实参传递
    66. defInfo.success(res)
    67. } catch (err) {
    68. // 执行失败回调---将接受的异常信息作为实参传递
    69. defInfo.error(err)
    70. }
    71. }
    72. }
    二、使用
    1. <script>
    2. // throw Error('异常了')
    3. ajax({
    4. url:'http://localhost:8888/users/login',
    5. // url:'http://localhost:8888/test/first',
    6. method:'post',
    7. data:{username:'admin',password:123456},
    8. // async:false,
    9. dataType:'json',
    10. // header:{'authorization':'123456','content-type':'application/json'},
    11. success:(res)=>{
    12. console.log( res )
    13. },
    14. error:(r)=>{
    15. console.log( r )
    16. }
    17. })
    18. script>

  • 相关阅读:
    【工具与中间件】Linux-Docker-Redis
    解决“org.apache.catalina.startup.Catalina.stopServer 未配置关闭端口。通过OS信号关闭服务器。服务器未关闭“
    极客日报:腾讯推出员工退休待遇方案;​百度高管称自动驾驶并非100%无事故;美国悬赏1500万美元通缉黑客
    java计算机毕业设计点餐平台网站源码+系统+程序+数据库+lw
    如何在ASO中使用App Store的促销文本
    linux上mysql 8.0安装
    设计模式
    Unity3D ugui获取ui控件屏幕坐标
    网络优化——修改MTU值提升网页访问速度
    SpringBoot拦截器Interceptor的使用-基础篇
  • 原文地址:https://blog.csdn.net/qq_48665028/article/details/139272957