react数据交互

    xiaoxiao2025-06-22  15

    数据交互

    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); });
    最新回复(0)