前置说明
- React本身只关注于界面, 并不包含发送ajax请求的代码
- 前端应用需要通过ajax请求与后台进行交互(json数据)
- react应用中需要集成第三方ajax库(或自己封装)
常用的ajax请求库
- jQuery: 比较重, 如果需要另外引入不建议使用
- axios: 轻量级, 建议使用
-
- 封装XmlHttpRequest对象的ajax
- promise风格
- 可以用在浏览器端和node服务器端
-
axios
文档
GitHub - axios/axios: Promise based HTTP client for the browser and node.js
相关API
- GET请求
axios.get('/user?ID=12345') .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); }); axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); |
2.POST请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); |
案例—github用户搜索
效果
请求地址: https://api.github.com/search/users?q=xxxxxx
消息订阅-发布机制
- 工具库: PubSubJS
- 下载: npm install pubsub-js --save
- 使用:
- import PubSub from 'pubsub-js' //引入
- PubSub.publish('delete', data) //发布消息
- PubSub.subscribe('delete', function(data){ }); //订阅
扩展:Fetch
文档
特点
- fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
- 老版本浏览器可能不支持
相关API
- GET请求
fetch(url).then(function(response) { return response.json() }).then(function(data) { console.log(data) }).catch(function(e) { console.log(e) }); |
2.POST请求
fetch(url, { method: "POST", body: JSON.stringify(data), }).then(function(data) { console.log(data) }).catch(function(e) { console.log(e) }) |