当前位置:   article > 正文

js Ajax函数封装及使用

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 src="./ajax.js"></script>
  2. <script>
  3. // throw Error('异常了')
  4. ajax({
  5. url:'http://localhost:8888/users/login',
  6. // url:'http://localhost:8888/test/first',
  7. method:'post',
  8. data:{username:'admin',password:123456},
  9. // async:false,
  10. dataType:'json',
  11. // header:{'authorization':'123456','content-type':'application/json'},
  12. success:(res)=>{
  13. console.log( res )
  14. },
  15. error:(r)=>{
  16. console.log( r )
  17. }
  18. })
  19. </script>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/655146
推荐阅读
相关标签
  

闽ICP备14008679号