Fetch、Axios 和 jQuery(Ajax) 三种常用的网络请求技术

news/2024/7/11 1:53:20 标签: jquery, ajax, axios, fetch, 网络请求

Fetch、Axios 和 jQuery(Ajax) 是三种常用的网络请求技术,它们各自有着不同的特点和优势。本文将对这三种技术进行详细的介绍和比较,以帮助开发者更好地选择和使用合适的网络请求技术。


一、Fetch

Fetch(浏览器自带) 是一种现代的网络请求 API,它是基于 Promise 设计的,可以用于替代传统的 XMLHttpRequest。Fetch 提供了一种更简洁、更强大的方式来处理网络请求和响应。

  1. 特点:
  • 基于 Promise 设计,支持异步操作;
  • 返回的 response 对象包含完整的响应信息,如状态码、响应头等;
  • 支持请求和响应的拦截;
  • 支持请求取消。
  1. 示例代码:
简单请求
fetch('http://loalhost:8080')
返回值
fetch('http://loalhost:8080')
  .then(response => response.json())
  .then(data => console.log(data))
表单方式提交
fetch('http://loalhost:8080',{
	method:'POST',
	headers:{'content-type':'application/x-www-form-urlencoded'},
	body:'age=18&t=183'
})
  .then(response => response.json())
  .then(data => console.log(data))
querystring方式提交
fetch('http://loalhost:8080?age=18',{
	method:'POST'
})
  .then(response => response.json())
  .then(data => console.log(data))
json方式提交
fetch('http://loalhost:8080',{
	method:'POST',
	headers:{'content-type':'application/json'},
	body:JSON.stringify({age:18})
})
  .then(response => response.json())
  .then(data => console.log(data))
返回error
fetch('http://loalhost:8080')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

二、Axios

Axios (前端后端都可用)是一个基于 Promise 的 HTTP 客户端,它可以在浏览器和 Node.js 环境中使用。Axios 提供了一种简单、易用的方式来处理网络请求和响应。

  1. 特点:
  • 支持浏览器和 Node.js 环境;
  • 自动转换 JSON 数据;
  • 支持拦截请求和响应;
  • 支持请求取消。
  1. bootcdn
    稳定、快速、免费的前端开源项目 CDN 加速服务
    在这里插入图片描述
    复制<script>标签
    在这里插入图片描述

浏览器测试

data:text/html,<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>

在这里插入图片描述

  1. 示例代码:
简单请求
axios({
    url:'http://localhost:8080'
})
默认json请求
axios({
    url:'http://localhost:8080',
    method:'POST',
    data:{age:18}
})
querystring方式提交
axios({
    url:'http://localhost:8080?age=18',
    method:'POST'
})
.then(response =>console.log(response .data))
表单方式提交
axios({
    url:'http://localhost:8080',
    method:'POST',
    headers:{'content-type':'application/x-www-form-urlencoded'},
    data:'age=18'
})
.then(response =>console.log(response .data))
返回error
axios({
    url:'http://localhost:8080',
    method:'POST',
    headers:{'content-type':'application/x-www-form-urlencoded'},
    data:'age=18'
})
.then(response =>console.log(response .data))
  .catch(error => {
    console.error(error);
  })

三、jQuery(Ajax)

jQuery 是一个流行的 JavaScript 库,它提供了一种简化的 Ajax 方法来处理网络请求和响应。虽然 jQuery 已经不再是前端开发的主流选择,但它仍然在一些项目中被广泛使用。

  1. 特点:
  • 兼容性好,支持多种浏览器;
  • 语法简单,易于上手;
  • 支持多种请求类型(如 GET、POST 等);
  • 支持请求和响应的回调函数。
  1. bootcdn
    稳定、快速、免费的前端开源项目 CDN 加速服务
    在这里插入图片描述
    复制<script>标签
    在这里插入图片描述

浏览器测试

data:text/html,<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

在这里插入图片描述

  1. 示例代码:
    在这里插入图片描述
简单请求
$.ajax({
  url: 'http://loalhost:8080'
})
返回值
$.ajax({
  url: 'http://loalhost:8080',
  success: function(data) {
    console.log(data);
  }
})
请求方法
$.ajax({
  method:'POST',
  url: 'http://loalhost:8080',
  success: function(data) {
    console.log(data);
  }
})
表单方式提交
$.ajax({
  method:'POST',
  data:{age:18},
  url: 'http://loalhost:8080',
  success: function(data) {
    console.log(data);
  }
})
querystring方式提交
$.ajax({
  method:'POST',
  data:{age:18},
  url: 'http://loalhost:8080',
  success: function(data) {
    console.log(data);
  }
})
json方式提交
$.ajax({
  method:'POST',
  headers:{'Content-Type':'application/json'},
  data:JSON.stringify({age:18}),
  url: 'http://loalhost:8080',
  success: function(data) {
    console.log(data);
  }
})

四、其他

// 基本用法无参数get请求
$.ajax({
    url:"demo_test.txt",
    success:function(result){
        console.log(result);
    }
}
// 需指定方法则增加method字段
$.ajax({
    url:"demo_test.txt",
    method:"POST",
    success:function(result){
	console.log(result);
    }
}
// 有参数,则增加data字段,有请求头则增加headers字段,有错误处理增加error字段
// 默认是按照表单提交post方法,data中虽然是json但是提交时转成表单
$.ajax({
    url:"demo_test.txt",
    data:{a:10},
    success:function(result){
    	console.log(result);
    },
    error:function(xhr,status,error){
    	console.log(error);
    }
});
// data在post下是表单格式,在get下是querystring格式
// 通过以下方法指定为json格式[json格式本质就是body里是json字符串,头里是application/json]
$.ajax({
    url:"demo_test.txt",
    headers:{ contentType: "application/json"},
    method:"POST",
    data:JSON.stringify({a:10}),
    success:function(result){
	console.log(result);
    }
});
// fetch的post表单数据用法
fetch(url,{
    headers:{
         'content-type': "application/x-www-form-urlencoded"
    },
    method:"POST",
    body:"age=18&w=213",
})
.then(res=>res.json())
.then(data=>console.log(res))
.catch(e=>{})
// fetch的post json数据用法
fetch(url,{
    headers:{
         'content-type': "application/json"
    },
    method:"POST",
    body:JSON.stringify({a:100}),
})
.then(res=>res.json())
.then(data=>console.log(res))
.catch(e=>{})
// axios默认是json类型的提交
axios({
    url:"http://localhost:8080?x=1",
    method:"POST",
    data:{age:18}
})
.then(res=>console.log(res.data))
// 如果想改成form则需要修改headers和data格式
axios({
    url:"http://localhost:8080?x=1",
    method:"POST",
    headers:{"Content-Type":"application/x-www-form-urlencoded"},
    data:"age=18&w=213"
})
.then(res=>console.log(res.data))
  • 简写

JQuery的get和post可以简写:

$.get(url,data,callback)  // querystring格式
$.post(url,data,callback) // x-www-form-urlencoded格式

axios的get/post/put/delete等等都可以简写

axios.post(url,data).then(callback)

五、总结

Fetch、Axios 和 jQuery(Ajax) 都是非常优秀的网络请求技术,它们各自有着不同的特点和优势。在选择使用哪种技术时,可以根据项目的需求和个人喜好来决定。例如,如果你需要一个轻量级、易于使用的库,可以选择 Axios;如果你需要更多的控制权和灵活性,可以选择 Fetch;如果你需要在旧版浏览器中保持兼容性,可以选择 jQuery(Ajax)。总之,了解这三种技术的优缺点,将有助于你更好地进行网络请求的处理。


http://www.niftyadmin.cn/n/5441147.html

相关文章

【移动端】AMap Flutter与Android AMap SDK交互

背景 本文的背景&#xff0c;是因为我在开发高德地图时&#xff0c;需要自定义高德比例尺位置和样式&#xff1b;但结果查看了AMap Flutter插件和AMap SDK源码后&#xff0c;发现AMap无法添加自定义MyMethodCallHandler的实现类&#xff01; why&#xff1f; 源码 在Flutte…

【Java.mysql】——数据删改(DU) 附加数据库约束

目录 &#x1f6a9;更新(Update) &#x1f6a9;删除&#xff08;Delete&#xff09; &#x1f6a9;数据库约束 &#x1f388;约束类型 ✅NULL约束 ✅NNIQUE 唯一约束 ✅DEFAULT&#xff1a;默认值约束 ✅PRIMARY KEY&#xff1a;主键约束 ✅FOREIGN KEY&#xff1a;外键…

JavaSE(上)-Day8

JavaSE&#xff08;上&#xff09;-Day8 Scanner拓展字符串APIStringString的初始化 究竟比较的是什么&#xff1f;StringBuilderStringJoiner字符串原理字符串的拼接原理 Scanner拓展 package com.itheima.day09.test;import java.util.Scanner;/*** 键盘录入扩展* * author …

如何利用MySQL建立覆盖原表的索引优化查询性能

MySQL数据库中&#xff0c;建立合适的索引对于提高查询性能至关重要。然而&#xff0c;在某些情况下&#xff0c;我们可能需要进一步优化查询性能&#xff0c;而覆盖索引&#xff08;Covering Index&#xff09;就是一种有效的方法。本文将介绍什么是覆盖索引以及如何在MySQL中…

在CentOS 7上使用Ansible安装Nginx

一、准备工作 安装Ansible (如果尚未安装)&#xff1a; 在Ansible控制节点&#xff08;通常是你的本地机器或CI/CD服务器&#xff09;上安装Ansible。 sudo yum install epel-release sudo yum install ansible设置Inventory&#xff1a; 编辑或创建Ansible的inventory文件&…

Nginx 配置 https 访问:SSL 免费证书申请并自动更新(完整命令篇)

阿里云 SSL 免费证书有效期从以前的一年调整为三个月&#xff0c;使用起来比较麻烦。 本文记录了在 CentOS 7.9 如何使用 acme.sh 完成免费证书的申请以及自动更新过程&#xff0c;再也不必为 SSL 证书过期而烦恼了。 acme.sh 是一个开源的纯shell 脚本编写的acme 客户端&…

uni-app 中两个系统各自显示不同的tabBar

最近在一个uni-app项目中遇到一个需求,在登录页面成功登录以后需要判断身份,不同的身份的进入不同的tabBar页面,但是在uni-app项目中pages.json中的tabBar的list数组只有一个&#xff0c;且不能写成动态的,那如何实现这个需求呢?答案是需要我们自定义tabBar。 目录 1、我们确…

Spring Boot 配置中心与应用属性完美匹配 | 深入探究@ConfigurationProperties与@NacosPropertySource

ConfigurationProperties ConfigurationProperties 注解是 Spring Boot 中用于将外部配置文件&#xff08;如 YAML 或 properties 文件&#xff09;中的属性映射到 Java Bean 类属性的强大工具。 以下是关于 ConfigurationProperties 注解与 YAML 配置文件属性匹配规则的详细…