react ajax
2020-03-03 本文已影响0人
hk_faith
简介
1,react 本身只关注界面,并不包含 ajax 请求的代码
2,前端需要应用通过 ajax 请求与后台进行交互(json数据)
3,react 应用中需要集成第三方 ajax库
常用的ajax 请求库
1,jQuery :比较重,如果需要另外引入不建议使用
2,fetch L:原生函数,但老版本浏览器不支持
3,axios :轻量级,建议使用
a, 封装 XmlHttpRequest 对象的 ajax
b, promise 风格
c, 可以用在浏览器端和node 服务器端
使用
Get 请求
axios.get('/user?ID=12345')
.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);
});
Post 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});