Ajax--axios

Ajax--axios

Ajax(Asynchronous Javascript And Xml)--异步js和xml

作用:

1.数据交互

向服务器发送请求,获取响应数据

2.异步交互

部分更新网页,不重新加载整个页面

同步交互和异步交互的区别

同步交互当客户端发送请求后需要等待响应

异步交互客户端发送请求后不需要,可以执行其他操作

如何发送Ajax异步请求

利用axios(封装了原生Ajax)发送请求,获取响应结果

1.引入src对应的js(官方提供)

2.调用axios 成功回调函数then 失败回调函数catch

()表示函数调用方式

{}封装对象,例如:method (post/get) url data(post) params等

params 是一个配置选项,用于在发送请求时向 URL 添加查询参数(query parameters)。

这些参数会以 key=value 的形式附加在 URL 后面,用 ? 与基础 URL 分隔,多个参数之间用 & 连接。

axios.get('/api/data', {
  params: {
    id: 123,
    name: 'example'
  }
})

即/api/data?id=123&name=example

<script src="axios官网js"></script>
axios({
  method:"post",
  url:"",
}).then((result)=>{
console.log(result.data);//成功回调函数
}).catch((err)=>{
alert(err);//失败回调函数
})

具体的操作

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax-axios</title>
</head>
<body>
  <input type="button" value="获取数据get" id="btnGet">
  <input type="button" value="操作数据post" id="btnPost">
  <script src="https://cdn.jsdelivr.***/npm/axios/dist/axios.min.js"></script>
  <script>
    //发送get请求
    document.querySelector('#btnGet').addEventListener('click',()=>{
        //axios发送异步请求
        axios({
          url:'https://mock.apifox.***/m1/3083103-0-default/emps/list',
          method:'GET'
        }).then((result)=>{//成功回调函数
          console.log(result.data)
        }).catch((err)=>{//失败回调函数
          console.log(err);
        })
    })
    //发送post请求
    document.querySelector('#btnPost').addEventListener('click',()=>{
      axios({
        url:'https://mock.apifox.***/m1/3083103-0-default/emps/update',
        method:'post',
        data:'id=1'//请求体数据
      }).then((result)=>{
        console.log(result.data)//成功回调函数
      }).catch((err)=>{
        console.log(err)//失败回调函数
      })
    })
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax-axios</title>
</head>

<body>
  <input type="button" value="获取数据get" id="btnGet">
  <input type="button" value="操作数据post" id="btnPost">
  <script src="https://cdn.jsdelivr.***/npm/axios/dist/axios.min.js"></script>
  <script>
    //发送get请求
    document.querySelector('#btnGet').addEventListener('click', () => {
      //axios发送异步请求
      axios.get('https://mock.apifox.***/m1/3083103-0-default/emps/list').then((result)=>{
        console.log(result.data);
      });
      console.log('000000')
    })
    //发送post请求
    document.querySelector('#btnPost').addEventListener('click', () => {
      //axios发送异步请求
      axios.post('https://mock.apifox.***/m1/3083103-0-default/emps/update').then((result) => {
        console.log(result.data);
      });
    })
  </script>
</body>

</html>

先输出000000异步请求不等待

转载请说明出处内容投诉
CSS教程网 » Ajax--axios

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买