fetch与ajax的优劣,Ajax fetch axios的区别与优缺点

Ajax  fetch axios的区别与优缺点

原生ajax:

var xhr=newXMLHttpRequest();

xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');

xhr.open('post','test.php');

xhr.send('name=test&age=18');

xhr.onreadystatechange=function(){if(xhr.readySate==4&&xhr.status==200){

console.log(xhr.responseText);

}

}

jqueryAjax

var btn=document.getElementById('btn');

btn.οnclick=function(){

ajax({

type:'post',

url:'test.php',

data:"name=test&&pwd=123456",

success:function(data){

console.log(data);

}

});

}

fetch

fetch('http://www.mozotech.cn/bangbang/index/user/login', {

method:'post',

headers: {'Content-Type': 'application/x-www-form-urlencoded'},

body:newURLSearchParams([

["username", "Lan"],["password", "123456"]

]).toString()

})

.then(res=>{

console.log(res);returnres.text();

})

.then(data=>{

console.log(data);

})

axios

axios.post({

url:'test.php',

data:{name:'test',age:18},

})

.then(res=>{console.log(res)})

.catch(error=>{console.log(error)});

同时发起多个请求:functiongetUserAccount(){return axios.get('user/123456')

}functiongetUserPermissions(){return axios.get('user/123456/permission')

}

axios.all([getUserAccount(),getUserPermission()])

.then(axios.spread((acct,perms)=>{

}))

对比

1 几种方式的对比

ajax:

优点:局部更新,原生支持

缺点:可能破坏浏览器后退功能,嵌套回调

jqueryAjax:

在原生ajax的基础上进行封装,支持jsonp

fetch:

优点:解决回调地狱

缺点:APIA偏低层,需要封装,默认不带cookie,需要手动添加;浏览器支持情况不是很友好,需要第三方polyfill

axios的特点:

支持浏览器和node.js

支持promise

能拦截请求和响应

能转换请求和相应数据

能取消请求

自动转换json数据

浏览器端支持防止CSRF(跨站请求伪造)

将axios异步请求同步处理:

async getInfo(){try{

let data=await axios.get('test.php');

console.log(data);

}catch(err){

console.log(err)

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值