Ajax-入门

Ajax: 全称Asynchronous JavaScript And XML,异步的JavaScript和XML。其作用有如下2点:

  • 与服务器进行数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。

  • 异步交互:可以在不重新加载整个页面 的情况下,与服务器交换数据并更新部分网页 的技术,如:搜索联想、用户名是否可用的校验等等

Axios

Axios的使用比较简单,主要分为2步:

1). 引入Axios文件

html 复制代码
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2). 点击按钮时,使用Axios发送请求

html 复制代码
<script>
    //GET请求
    document.querySelector('#getData').onclick = function() {
      //axios发送异步请求
      axios({
        url:'https://mock.apifox.cn/m1/3083103-0-default/emps/list',
        method:'get'
      }).then(function(res) {
        console.log(res.data);
      }).catch(function(err) {
        console.log(err);
      })
    }
    
    //POST请求
    document.querySelector('#postData').onclick = function() {
      axios({
        url:'https://mock.apifox.cn/m1/3083103-0-default/emps/update',
        method:'post'
      }).then(function(res) {
//成功回调函数
        console.log(res.data);
      }).catch(function(err) {
//失败回调函数
        console.log(err);
      })
    }
  </script>

Axios还针对不同的请求,提供了别名方式的api,具体格式如下:

axios.请求方式(url [, data [, config]])

具体如下:

|----------------------------------------|------------|
| 方法 | 描述 |
| axios.get(url [, config]) | 发送get请求 |
| axios.delete(url [, config]) | 发送delete请求 |
| axios.post(url [, data[, config]]) | 发送post请求 |
| axios.put(url [, data[, config]]) | 发送put请求 |

改写

javascript 复制代码
axios.get("https://mock.apifox.cn/m1/3083103-0-default/emps/list").then(result => {
    console.log(result.data);
})
javascript 复制代码
axios.post("https://mock.apifox.cn/m1/3083103-0-default/emps/update","id=1").then(result => {
    console.log(result.data);
})
相关推荐
布列瑟农的星空3 分钟前
大话设计模式——关注点分离原则下的事件处理
前端·后端·架构
山有木兮木有枝_6 分钟前
node文章生成器
javascript·node.js
yvvvy22 分钟前
前端必懂的 Cache 缓存机制详解
前端
北海几经夏37 分钟前
React自定义Hook
前端·react.js
龙在天42 分钟前
从代码到屏幕,浏览器渲染网页做了什么❓
前端
TimelessHaze43 分钟前
【performance面试考点】让面试官眼前一亮的performance性能优化
前端·性能优化·trae
yes or ok1 小时前
前端工程师面试题-vue
前端·javascript·vue.js
我要成为前端高手1 小时前
给不支持摇树的三方库(phaser) tree-shake?
前端·javascript
Noxi_lumors1 小时前
VITE BALABALA require balabla not supported
前端·vite
周胜21 小时前
node-sass
前端