ajax,fetch,axios的区别及运用

浅浅的花香味﹌ 2022-10-01 07:56 274阅读 0赞

AJAX

  • 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
  • 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
  • 传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
1. ajax的封装(创建myajax.js 文件夹)
  1. /** * { * method:get, * url: '/login.do', * content: 'username=admin&password=123' * success: functon(e){ * * } * } * * * * @param {*} json */
  2. function myajax(json) {
  3. // 1. 获取 XmlHttpRequest
  4. var xhr = getXHR();
  5. // 2. 打开连接发送请求
  6. xhr.open(json.method, json.url, true);
  7. xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 请求头部
  8. xhr.send(json.content);
  9. // 3. 处理响应
  10. xhr.onreadystatechange = function (e) {
  11. // 根据就绪码判断响应是否完成
  12. if (e.target.readyState === 4) {
  13. // 根据状态码判断成功失败
  14. if (e.target.status === 200) {
  15. /* console.log(e.target.responseText); alert('响应内容是 :' + e.target.responseText); */
  16. json.success(e.target.responseText);
  17. }
  18. }
  19. }
  20. }
  21. function getXHR() {
  22. if (window.XMLHttpRequest) {
  23. return new window.XMLHttpRequest;
  24. } else {
  25. // 兼容IE浏览器低版本
  26. new window.AtiveXObject("Microsoft.XMLHTTP");
  27. }
  28. }
  29. export default myajax; //暴露出去
2.调用myajax
  1. myajax({
  2. method: "post", //请求方式post get
  3. url: "http://127.0.0.1:8089/api/login", //请求地址
  4. content: `username=${ username}&password=${ password}`, //请求正文
  5. success: function(e) { //成功的函数回调
  6. const data = JSON.parse(e);
  7. if (data.resultcode === -1) { //接口文档中给的参数,判断是否等于-1
  8. //登录失败
  9. that.message = data.resultinfo;
  10. } else {
  11. //登录成功
  12. that.$router.replace({ path: "/main" });
  13. }
  14. }
  15. });

Fetch

  • fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
  • -优势
  1. 语法简洁,更加语义化
  2. 基于标准 Promise 实现,支持 async/await
  3. 同构方便,使用 isomorphic-fetch
  4. 更加底层,提供的API丰富(request, response)
  5. 脱离了XHR
fetch使用代码
  1. ---get请求---
  2. // 通过fetch获取百度的错误提示页面
  3. fetch('https://www.baidu.com/search/error.html', {
  4. method: 'GET'
  5. })
  6. .then((res)=>{
  7. return res.text() // res.json();
  8. })
  9. .then((res)=>{
  10. console.log(res)
  11. })
  12. ---post请求---
  13. // 通过fetch获取百度的错误提示页面
  14. fetch('https://www.baidu.com/search/error.html', {
  15. method: 'POST',
  16. body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象
  17. })
  18. .then((res)=>{
  19. return res.text()
  20. })
  21. .then((res)=>{
  22. console.log(res)
  23. })

Axios

-axios主要是jQuery的ajax与fetch的融合,十分强大

  • 特点
  1. 支持浏览器和node.js
  2. 支持promise(重点)
  3. 能拦截请求和响应
  4. 能转换请求和响应数据
  5. 能取消请求
  6. 自动转换JSON数据
  7. 浏览器端支持防止CSRF(跨站请求伪造)
1. 安装
  1. npm install axios //然后在需要的地方调用
2. 安装
  1. axios({
  2. method: 'post', //请求方式
  3. url: '/user/12345', //请求地址
  4. data: { //请求数据
  5. firstName: 'Fred',
  6. lastName: 'Flintstone'
  7. }
  8. }).then(res=>{
  9. console.log(`成功的回调${ res}`)
  10. }).catch(err=>{
  11. console.log(`错误的回调${ err}`)
  12. });

发表评论

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

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

相关阅读

    相关 nextTick 理解运用

    nextTick 1.触发的时候 同步的话 就是等数据渲染完成之后执行 跟所在位置的上下文没有关系 2.触发的时候 异步的话 等异步的数据时间 如果时间短

    相关 异或性质运用

    异或是一种基于二进制的位运算,用符号XOR或者 ^ 表示,其运算法则是对运算符两侧数的每一个二进制位,同值取0,异值取1。它与布尔运算的区别在于,当运算符两侧均为1时,布尔运算