1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 前端 3 种Ajax请求方式(jQuery/axios/fetch)详解

前端 3 种Ajax请求方式(jQuery/axios/fetch)详解

时间:2020-02-19 16:32:32

相关推荐

前端 3 种Ajax请求方式(jQuery/axios/fetch)详解

前端 3 种Ajax请求方式 jQuery/axios/fetch 详解

前言一、jQuery二、axios三、fetch四、总结

前言

目前市面上前端请求接口的主流方式是 Ajax(Asynchronous JavaScript and XML),而封装的 Ajax 有 3 种,在单页面应用还没出现的时候,最原始的 jQuery 使用最频繁。后来 axios 与 fetch 也相继而出。本文主要分享这 3 种 Ajax 请求方式的使用与异同。

一、jQuery

$.get

//只请求网页或数据,没有返回值$.get(url)//只请求网页或数据,传递参数,没有返回值$.get(url,{id:123})//请求网页或数据,有返回值$.get(url,(res)=>{alert(res);})//请求网页或数据,同时传递参数,有返回值$.get(url,{id:123},(res)=>{alert(res);})//完整的方式如下$.get(url,data,success(response,status,xhr),dataType)

$.post

$.post(url,//请求的URL地址data,//请求参数success(data, textStatus, jqXHR),//回调函数dataType //规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或 html)。)

$.ajax

$.ajax({type: "POST",//请求方式,默认值GETdata:{id:123},//请求参数,自动转换为字符串格式,如果是get请求,会自动拼接到url上面url: "test.html", //请求地址context: document.body, //绑定回调中的thisasync:true,//是否是异步请求,默认情况下都是true,如果要发送同步请求,则改为falsecache:false,//是否返回此页面,默认值为truedataType: "json",jsonp:"callback",//在一个jsonp请求中重写回调函数的名字。//规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或 html)。contentType:"application/x-www-form-urlencoded",//发送数据至服务器内容编码类型success: function(){$(this).addClass("done");}});

二、axios

通过get方式获取

//方式一axios.get('/user?id=123').then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});// 方式二axios.get('/user', {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});//方式三axios({url: ' http://localhost/xxx.php ',params:{id:123}}).then( res =>console.log(res) ).catch(error => if(error) throw error)

通过 post 方式获取

//方式一axios.post('/user', {id: '123'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});//方式二var params = new URLSearchParams();params.append( 属性,属性值 )params.append( 属性,属性值 )axios({url:'http://localhost/xxx.php',method:'post',headers: {//只对此模板有效 'Content-Type': 'application/x-www-form-urlencoded'},//传参data:params;}).then( res =>console.log(res) ).catch(error =>{if(error)=>throw error})

直接使用

var params = new URLSearchParams();params.append( 属性,属性值 )params.append( 属性,属性值 )axios({url:'http://localhost/xxx.php',method:'post',//根据不同的请求方式传不同的参数,默认为GETbaseURL:"https://some-/api/",//为请求加一个前缀,通常用于环境配置headers: {//只对此模板有效 'Content-Type': 'application/x-www-form-urlencoded'},//传参data:params;}).then( res =>console.log(res) ).catch(error =>{if(error)=>throw error})

执行多个并发请求

function getUserAccount() {return axios.get('/user/12345');}function getUserPermissions() {return axios.get('/user/12345/permissions');}axios.all([getUserAccount(), getUserPermissions()]).then(axios.spread(function (acct, perms) {// 两个请求现在都执行完成}));

三、fetch

通过 get 方式获取

fetch({http://localhost/xxx.php?a=1&b=3}).then(res => res.text())//与axios不同的一点是得到的数据需要转义.then(data => console.log(data)).catch(error => {if (error) throw error})//get方法传参的形式 很像form表单中通过get传递数据时,会在浏览器地址栏显示的形式一样。

通过 post 方式获取

fetch('http://localhost/xxx.php',{method: 'post',headers: new Headers({//解决跨域'Content-Type': "application/x-www-form-urlencoded"}),body: new URLSearchParams([['a', 1],['b', 20]]).toString()}).then(res => res.text()).then(data => console.log(data)).catch(error => {if (error) throw error})

直接使用

fetch(url, {body: JSON.stringify(data), //请求报文cache: 'no-cache', //是否缓存页面,取值有 *default, no-cache, reload, force-cache, only-if-cachedcredentials: 'same-origin', // 是否带有包含凭证的请求,取值有include, same-origin, *omitheaders: {'content-type': 'application/json'},method: 'POST', // 请求方式自定义,支持*GET, POST, PUT, DELETE等mode: 'cors', // 是否启用cors策略,取值有no-cors, cors})

四、总结

对比三种封装的请求方式

通过 post 请求发送报文,jQuery 和 axios 对应的 key 都是 data,需要说明的是当 axios 为 get 请求时,对应的 key 是 params。而 fetch 对应的 key 则是 body,如果不是 FormData 对象,需要转换为字符串,并且返回结果也需要转换为 json 格式。jQuery 和 axios 除了自定义配置外,都有对应的别名方法,如 . g e t , .get, .get,.post,axios.get,axios.post,fetch 则没有。axios 和 fetch 主要是基于 promise 的封装,所以都有 then 方法。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。