前端 3 种Ajax请求方式(jQuery/axios/fetch)详解 前言 一、jQuery 二、axios 三、fetch 四、总结 前言 目前市面上前端请求接口的主流方式是 Ajax(Asynchronous JavaScript and XML),而封装的 Ajax 有 3 种,在单页面应用还没出现的时候,最原始的 jQuery 使用最频繁。后来 axios 与 fetch 也相继而出。本文主要分享这 3 种 Ajax 请求方式的使用与异同。
$.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",//请求方式,默认值GET data:{id:123},//请求参数,自动转换为字符串格式,如果是get请求,会自动拼接到url上面 url: "test.html", //请求地址 context: document.body, //绑定回调中的this async:true,//是否是异步请求,默认情况下都是true,如果要发送同步请求,则改为false cache:false,//是否返回此页面,默认值为true dataType: "json", jsonp:"callback",//在一个jsonp请求中重写回调函数的名字。 //规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或 html)。 contentType:"application/x-www-form-urlencoded",//发送数据至服务器内容编码类型 success: function(){ $(this).addClass("done"); } });通过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',//根据不同的请求方式传不同的参数,默认为GET baseURL:"https://some-domain.com/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) { // 两个请求现在都执行完成 }));通过 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-cached credentials: 'same-origin', // 是否带有包含凭证的请求,取值有include, same-origin, *omit headers: { '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 除了自定义配置外,都有对应的别名方法,如 .get,.get,.post,axios.get,axios.post,fetch 则没有。 axios 和 fetch 主要是基于 promise 的封装,所以都有 then 方法。
参考http://www.cocoachina.com/cms/wap.php?action=article&id=35376
