讲解Ajax和axios相关知识

绝地灬酷狼 2024-04-17 06:39 155阅读 0赞

文章目录

  • ?简述Ajax
    • ⭐作用
  • ?异步请求&&同步请求
    • ⭐同步
    • ⭐异步
  • ?原生Ajax(复杂,不建议使用,可以帮助理解)
  • ?axios
    • ?axios入门
      • ?代码实现

?简述Ajax

Ajax(Asynchronous JavaScript and XML)是一种网页开发技术,通过使用 JavaScript 和 XML(现在更常用的是 JSON)实现在不重新加载整个页面的情况下更新部分页面内容的功能。相比传统的同步请求方式,Ajax 可以异步地向服务器发送请求并接收响应,使得用户可以在无需等待页面全部加载完成的情况下获取该页面部分数据的更新。

⭐作用

  • 实时更新:通过 Ajax 技术,网页可以在不刷新整个页面的情况下,动态地更新部分内容,如加载新的数据、评论、消息等。这种实时更新可以大大提高用户体验,减少用户等待时间。
  • 表单验证:使用 Ajax 技术可以实现表单的即时验证,当用户填写完表单的某一项内容后,可以立即向服务器发送请求进行验证,而不需要等待整个表单提交后才得到反馈。
  • 动态加载:当需要动态加载内容时,比如在网页滚动到底部时自动加载更多内容,或者通过搜索框输入关键词后自动展示相关内容,都可以通过 Ajax 技术实现。
  • 提升响应速度:由于 Ajax 可以异步请求数据,因此网页可以在后台获取数据的同时继续响应用户的操作,提升了网页的响应速度。

?异步请求&&同步请求

请添加图片描述

⭐同步

简而言之,同步就是我们点击某个超链接之类的操作

⭐异步

我们在浏览器输入的时候,比如我们输入Java,下面就会自动出来一些关于Java的词条,但是现在浏览器没有刷新,这就是异步操作
在这里插入图片描述

?原生Ajax(复杂,不建议使用,可以帮助理解)

请添加图片描述

原生Ajax
首先我们要准备一个数据地址http://yapi.smart-xwork.cn/mock/169327/emp/list,然后写入下面的代码

运行后发现
但是我们发现这种方法太复杂了,不利于我们开发使用
下面我们介绍一种简单的方法,axios

?axios

axios就是对原生的Ajax进行了封装,简化书写

官网https://www.axios-http.cn/

Axios 主要有以下特点:

基于 Promise 实现: Axios 提供的 API 返回的是 Promise 对象,使得异步请求更加方便和可读。

支持拦截器: 支持请求和响应拦截器,可以在请求被发送或响应被接收之前对其进行拦截和修改,可用于设置公共请求头、loading 状态提示、错误处理等。

支持并发请求:可以一次性发起多个请求,并且在所有请求完成后返回结果。

自动转换数据类型:Axios 能够根据响应数据类型自动转换为 JSON 对象。

支持取消请求:Axios 支持取消请求,可以在请求未完成时中断请求。

?axios入门

请添加图片描述

?代码实现

首先引入js文件
在这里插入图片描述
在这里插入图片描述

  1. /* axios v0.18.0 | (c) 2018 by Matt Zabriskie */
  2. !function(e,t){
  3. "object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){
  4. return function(e){
  5. function t(r){
  6. if(n[r])return n[r].exports;var o=n[r]={
  7. exports:{
  8. },id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={
  9. };return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){
  10. e.exports=n(1)},function(e,t,n){
  11. "use strict";function r(e){
  12. var t=new s(e),n=i(s.prototype.request,t);return o.extend(n,s.prototype,t),o.extend(n,t),n}var o=n(2),i=n(3),s=n(5),u=n(6),a=r(u);a.Axios=s,a.create=function(e){
  13. return r(o.merge(u,e))},a.Cancel=n(23),a.CancelToken=n(24),a.isCancel=n(20),a.all=function(e){
  14. return Promise.all(e)},a.spread=n(25),e.exports=a,e.exports.default=a},function(e,t,n){
  15. "use strict";function r(e){
  16. return"[object Array]"===R.call(e)}function o(e){
  17. return"[object ArrayBuffer]"===R.call(e)}function i(e){
  18. return"undefined"!=typeof FormData&&e instanceof FormData}function s(e){
  19. var t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function u(e){
  20. return"string"==typeof e}function a(e){
  21. return"number"==typeof e}function c(e){
  22. return"undefined"==typeof e}function f(e){
  23. return null!==e&&"object"==typeof e}function p(e){
  24. return"[object Date]"===R.call(e)}function d(e){
  25. return"[object File]"===R.call(e)}function l(e){
  26. return"[object Blob]"===R.call(e)}function h(e){
  27. return"[object Function]"===R.call(e)}function m(e){
  28. return f(e)&&h(e.pipe)}function y(e){
  29. return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}function w(e){
  30. return e.replace(/^\s*/,"").replace(/\s*$/,"")}function g(){
  31. return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function v(e,t){
  32. if(null!==e&&"undefined"!=typeof e)if("object"!=typeof e&&(e=[e]),r(e))for(var n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}function x(){
  33. function e(e,n){
  34. "object"==typeof t[n]&&"object"==typeof e?t[n]=x(t[n],e):t[n]=e}for(var t={
  35. },n=0,r=arguments.length;n<r;n++)v(arguments[n],e);return t}function b(e,t,n){
  36. return v(t,function(t,r){
  37. n&&"function"==typeof t?e[r]=E(t,n):e[r]=t}),e}var E=n(3),C=n(4),R=Object.prototype.toString;e.exports={
  38. isArray:r,isArrayBuffer:o,isBuffer:C,isFormData:i,isArrayBufferView:s,isString:u,isNumber:a,isObject:f,isUndefined:c,isDate:p,isFile:d,isBlob:l,isFunction:h,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:g,forEach:v,merge:x,extend:b,trim:w}},function(e,t){
  39. "use strict";e.exports=function(e,t){
  40. return function(){
  41. for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t){
  42. function n(e){
  43. return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function r(e){
  44. return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}/*!
  45. * Determine if an object is a Buffer
  46. *
  47. * @author Feross Aboukhadijeh <https://feross.org>
  48. * @license MIT
  49. */
  50. e.exports=function(e){
  51. return null!=e&&(n(e)||r(e)||!!e._isBuffer)}},function(e,t,n){
  52. "use strict";function r(e){
  53. this.defaults=e,this.interceptors={
  54. request:new s,response:new s}}var o=n(6),i=n(2),s=n(17),u=n(18);r.prototype.request=function(e){
  55. "string"==typeof e&&(e=i.merge({
  56. url:arguments[0]},arguments[1])),e=i.merge(o,{
  57. method:"get"},this.defaults,e),e.method=e.method.toLowerCase();var t=[u,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){
  58. t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){
  59. t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},i.forEach(["delete","get","head","options"],function(e){
  60. r.prototype[e]=function(t,n){
  61. return this.request(i.merge(n||{
  62. },{
  63. method:e,url:t}))}}),i.forEach(["post","put","patch"],function(e){
  64. r.prototype[e]=function(t,n,r){
  65. return this.request(i.merge(r||{
  66. },{
  67. method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){
  68. "use strict";function r(e,t){
  69. !i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function o(){
  70. var e;return"undefined"!=typeof XMLHttpRequest?e=n(8):"undefined"!=typeof process&&(e=n(8)),e}var i=n(2),s=n(7),u={
  71. "Content-Type":"application/x-www-form-urlencoded"},a={
  72. adapter:o(),transformRequest:[function(e,t){
  73. return s(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){
  74. if("string"==typeof e)try{
  75. e=JSON.parse(e)}catch(e){
  76. }return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){
  77. return e>=200&&e<300}};a.headers={
  78. common:{
  79. Accept:"application/json, text/plain, */*"}},i.forEach(["delete","get","head"],function(e){
  80. a.headers[e]={
  81. }}),i.forEach(["post","put","patch"],function(e){
  82. a.headers[e]=i.merge(u)}),e.exports=a},function(e,t,n){
  83. "use strict";var r=n(2);e.exports=function(e,t){
  84. r.forEach(e,function(n,r){
  85. r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){
  86. "use strict";var r=n(2),o=n(9),i=n(12),s=n(13),u=n(14),a=n(10),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(15);e.exports=function(e){
  87. return new Promise(function(t,f){
  88. var p=e.data,d=e.headers;r.isFormData(p)&&delete d["Content-Type"];var l=new XMLHttpRequest,h="onreadystatechange",m=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in l||u(e.url)||(l=new window.XDomainRequest,h="onload",m=!0,l.onprogress=function(){
  89. },l.ontimeout=function(){
  90. }),e.auth){
  91. var y=e.auth.username||"",w=e.auth.password||"";d.Authorization="Basic "+c(y+":"+w)}if(l.open(e.method.toUpperCase(),i(e.url,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,l[h]=function(){
  92. if(l&&(4===l.readyState||m)&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))){
  93. var n="getAllResponseHeaders"in l?s(l.getAllResponseHeaders()):null,r=e.responseType&&"text"!==e.responseType?l.response:l.responseText,i={
  94. data:r,status:1223===l.status?204:l.status,statusText:1223===l.status?"No Content":l.statusText,headers:n,config:e,request:l};o(t,f,i),l=null}},l.onerror=function(){
  95. f(a("Network Error",e,null,l)),l=null},l.ontimeout=function(){
  96. f(a("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",l)),l=null},r.isStandardBrowserEnv()){
  97. var g=n(16),v=(e.withCredentials||u(e.url))&&e.xsrfCookieName?g.read(e.xsrfCookieName):void 0;v&&(d[e.xsrfHeaderName]=v)}if("setRequestHeader"in l&&r.forEach(d,function(e,t){
  98. "undefined"==typeof p&&"content-type"===t.toLowerCase()?delete d[t]:l.setRequestHeader(t,e)}),e.withCredentials&&(l.withCredentials=!0),e.responseType)try{
  99. l.responseType=e.responseType}catch(t){
  100. if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){
  101. l&&(l.abort(),f(e),l=null)}),void 0===p&&(p=null),l.send(p)})}},function(e,t,n){
  102. "use strict";var r=n(10);e.exports=function(e,t,n){
  103. var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){
  104. "use strict";var r=n(11);e.exports=function(e,t,n,o,i){
  105. var s=new Error(e);return r(s,t,n,o,i)}},function(e,t){
  106. "use strict";e.exports=function(e,t,n,r,o){
  107. return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e}},function(e,t,n){
  108. "use strict";function r(e){
  109. return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){
  110. if(!t)return e;var i;if(n)i=n(t);else if(o.isURLSearchParams(t))i=t.toString();else{
  111. var s=[];o.forEach(t,function(e,t){
  112. null!==e&&"undefined"!=typeof e&&(o.isArray(e)?t+="[]":e=[e],o.forEach(e,function(e){
  113. o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),s.push(r(t)+"="+r(e))}))}),i=s.join("&")}return i&&(e+=(e.indexOf("?")===-1?"?":"&")+i),e}},function(e,t,n){
  114. "use strict";var r=n(2),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){
  115. var t,n,i,s={
  116. };return e?(r.forEach(e.split("\n"),function(e){
  117. if(i=e.indexOf(":"),t=r.trim(e.substr(0,i)).toLowerCase(),n=r.trim(e.substr(i+1)),t){
  118. if(s[t]&&o.indexOf(t)>=0)return;"set-cookie"===t?s[t]=(s[t]?s[t]:[]).concat([n]):s[t]=s[t]?s[t]+", "+n:n}}),s):s}},function(e,t,n){
  119. "use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){
  120. function e(e){
  121. var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{
  122. href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){
  123. var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){
  124. return function(){
  125. return!0}}()},function(e,t){
  126. "use strict";function n(){
  127. this.message="String contains an invalid character"}function r(e){
  128. for(var t,r,i=String(e),s="",u=0,a=o;i.charAt(0|u)||(a="=",u%1);s+=a.charAt(63&t>>8-u%1*8)){
  129. if(r=i.charCodeAt(u+=.75),r>255)throw new n;t=t<<8|r}return s}var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";n.prototype=new Error,n.prototype.code=5,n.prototype.name="InvalidCharacterError",e.exports=r},function(e,t,n){
  130. "use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){
  131. return{
  132. write:function(e,t,n,o,i,s){
  133. var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){
  134. var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){
  135. this.write(e,"",Date.now()-864e5)}}}():function(){
  136. return{
  137. write:function(){
  138. },read:function(){
  139. return null},remove:function(){
  140. }}}()},function(e,t,n){
  141. "use strict";function r(){
  142. this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){
  143. return this.handlers.push({
  144. fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){
  145. this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){
  146. o.forEach(this.handlers,function(t){
  147. null!==t&&e(t)})},e.exports=r},function(e,t,n){
  148. "use strict";function r(e){
  149. e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),i=n(19),s=n(20),u=n(6),a=n(21),c=n(22);e.exports=function(e){
  150. r(e),e.baseURL&&!a(e.url)&&(e.url=c(e.baseURL,e.url)),e.headers=e.headers||{
  151. },e.data=i(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{
  152. },e.headers[e.method]||{
  153. },e.headers||{
  154. }),o.forEach(["delete","get","head","post","put","patch","common"],function(t){
  155. delete e.headers[t]});var t=e.adapter||u.adapter;return t(e).then(function(t){
  156. return r(e),t.data=i(t.data,t.headers,e.transformResponse),t},function(t){
  157. return s(t)||(r(e),t&&t.response&&(t.response.data=i(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){
  158. "use strict";var r=n(2);e.exports=function(e,t,n){
  159. return r.forEach(n,function(n){
  160. e=n(e,t)}),e}},function(e,t){
  161. "use strict";e.exports=function(e){
  162. return!(!e||!e.__CANCEL__)}},function(e,t){
  163. "use strict";e.exports=function(e){
  164. return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){
  165. "use strict";e.exports=function(e,t){
  166. return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t){
  167. "use strict";function n(e){
  168. this.message=e}n.prototype.toString=function(){
  169. return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){
  170. "use strict";function r(e){
  171. if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){
  172. t=e});var n=this;e(function(e){
  173. n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(23);r.prototype.throwIfRequested=function(){
  174. if(this.reason)throw this.reason},r.source=function(){
  175. var e,t=new r(function(t){
  176. e=t});return{
  177. token:t,cancel:e}},e.exports=r},function(e,t){
  178. "use strict";e.exports=function(e){
  179. return function(t){
  180. return e.apply(null,t)}}}])});
  181. //# sourceMappingURL=axios.min.map

下面编写代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="js/axios-0.18.0.js"></script>
  8. </head>
  9. <body>
  10. <input type="button" value="获取数据get" onclick="get()">
  11. <input type="button" value="删除数据post" onclick="post()">
  12. </body>
  13. <script>
  14. function get(){
  15. //通过axios发送异步请求-get
  16. axios({
  17. methods:"get",
  18. url:"http://yapi.smart-xwork.cn/mock/169327/emp/list"
  19. }).then(result=>{
  20. console.log(result.data)
  21. })
  22. }
  23. function post(){
  24. //通过axios发送异步请求-post
  25. axios({
  26. method:"post",
  27. url:"http://yapi.smart-xwork.cn/mock/169327/emp/deleteById",
  28. data:"id=1"
  29. }).then(result=>{
  30. console.log(result.data)
  31. })
  32. }
  33. </script>
  34. </html>

在技术的道路上,我们不断探索、不断前行,不断面对挑战、不断突破自我。科技的发展改变着世界,而我们作为技术人员,也在这个过程中书写着自己的篇章。让我们携手并进,共同努力,开创美好的未来!愿我们在科技的征途上不断奋进,创造出更加美好、更加智能的明天!

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,155人围观)

还没有评论,来说两句吧...

相关阅读