react数据交互

数据交互

React没有集成ajax功能,要使用ajax功能,可以使用官方推荐的axios.js库来做ajax的交互。 axios库的下载地址:https://github.com/axios/axios/releases

axios使用方法

常用参数:
1、url 请求地址
2、method 请求方式,默认是'GET',常用的还有'POST'
3、responsetype 设置返回的数据格式,常用的是'json'格式,也可以设置为'text'或者'html'
4、params 设置发送给服务器的数据
5、then 设置请求成功后的回调函数
6、catch 设置请求失败后的回调函数

axios完整写法:

axios({
  url: '/user/12345',
  method: 'get',
  responsetype:'json',
  params: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

axios请求的写法也写成get方式后post方式。

执行get请求

// 为给定 ID 的 user 创建请求
// then是请求成功时的响应,catch是请求失败时的响应

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);
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值