1. 什么是 axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
2. axios 学习资源
axios中文网:http://www.axios-js.com
github仓库地址:https://github.com/axios/axios
3. 使用示例
<script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>
axios.get('http://127.0.0.1/1.php')
.then(res=>{
// 接口数据
console.log(res.data)
})</script>
4. 发送get请求,携带参数
**请求参数属性: params: {} **
axios.get('http://127.0.0.1/1.php', {
params: {
id: 1,
name: 'liang'
}}).then(res=>{
// 接口数据
console.log(res.data)})
5. 发送post请求,携带参数
参数直接作为axios.post() 的第二个参数,而不像get请求需要写在 params 中
axios.post('http://127.0.0.1/1.php', {
id: 1,
name: 'liang'}).then(res=>{
console.log(res.data)})
特别注意:PHP则需要使用以下方式接收POST数据 $_POST是接收不到的
file_get_contents('php://input');
解决方案:使用Qs处理下数据,此时PHP可以使用$_POST接收到参数了
在bootcdn搜索qs,引入qs的cdn,使用 Qs.stringify 处理数据
<script src="https://unpkg.com/axios/dist/axios.min.js"></script><!-- 引入 qs 在bootcdn搜索qs --><script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js"></script><script>
axios.post('http://127.0.0.1/1.php', Qs.stringify({
id: 1,
name: 'liang'
}))
.then(res=>{
console.log(res.data)
})</script>
6. axios 全能型
get
axios({
url: 'http://127.0.0.1/1.php',
method: 'get',
params: {id: 1}}).then(res => {
console.log(res.data)})
post
axios({
url: 'http://127.0.0.1/1.php',
method: 'post',
data: Qs.stringify({id: 1})}).then(res => {
console.log(res.data)})
7. xm-select
推荐一个下拉多选的插件,该插件文档中的示例,也是使用的axios
xm-select:https://gitee.com/maplemei/xm-select
