[JavaScript][AJAX] axios框架 ,页面跳转传参,DOM驱动,数据驱动渲染页面,tab切换,网络请求loading动画

目录

axios框架

axios基本语法

axios推荐使用方式

axios注意点:

 js中分号作用

页面跳转传参

DOM驱动渲染页面

数据驱动渲染页面

tab切换

网络请求loading动画


axios框架

Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

axios基本语法

      axios基本语法

     1.基本语法 : axios.get('url' ) .then( res=>{} ).catch( err=>{} )

      1.1 get请求: axios.get('url , {params:{ 属性名:属性值 }}). then(res=>{})

      1.2 post请求: axios.post('url', { 属性名:属性值 } ). then( res=> {} )

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <style>
    .box {
      height: 200px;
      width: 800px;
      font-size: 20px;
      font-weight: 700;
      margin: 20px auto;
    }
  </style>
</head>

<body>
  <button class="btn1">基本使用</button>
  <button class="btn2">点我发送get请求</button>
  <button class="btn3">点我发送post请求</button>
  <div class="box"></div>
  <!-- 引入 -->
  <script src="./axios.js"></script>
  <script>
    /*
      axios基本语法
     1.基本语法 : axios.get('url' ) .then( res=>{} ).catch( err=>{} )
      1.1 get请求: axios.get('url , {params:{ 属性名:属性值 }}). then(res=>{})
      1.2 post请求: axios.post('url', { 属性名:属性值 } ). then( res=> {} )

      3.axios注意点:res对象并不是服务器响应的原始数据,而是axios自己额外包的数据
res.config:请求配置
res.data:服务器真正响应的数据


*/
    document.querySelector('.btn1').addEventListener('click', function () {
      axios.get('https://autumnfish.cn/api/joke/list?num=10')
        // .then代替onload
        .then(res => console.log(res))
        .catch(err => console.log(err))
    })
    document.querySelector('.btn2').addEventListener('click', function () {
      axios.get('https://autumnfish.cn/api/joke/list', {
        // 参数
        params: { num: 10 }
      }).then(res => {
        console.log(res);
        document.querySelector('.box').innerHTML = res.data.data
      })
    })
    document.querySelector('.btn3').addEventListener('click', function () {
      axios.post('http://ajax-base-api-t.itheima.net/api/login', { username: 'admin', password: '123456' }).then(res => {
        console.log(res)
        alert(res.data.msg)
      })
    })
  </script>
</body>

</html>

axios推荐使用方式

💎推荐语法:

    axios({

      method:'请求方法',

      url:'请求路径',

      params:{get参数},

      data:{post参数}

    })

💎注意:params传get方法参数,data传post参数,不要错用,错用无效

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <style>
    .box {
      height: 200px;
      width: 800px;
      font-size: 20px;
      font-weight: 700;
      margin: 20px auto;
    }
  </style>
</head>

<body>
  <button class="btn1">基本使用</button>
  <button class="btn2">点我发送get请求</button>
  <button class="btn3">点我发送post请求</button>
  <div class="box"></div>
  <!-- 引入 -->
  <script src="./axios.js"></script>
  <script>
 
    document.querySelector('.btn1').addEventListener('click', function () {
 
      axios({
        url: 'https://autumnfish.cn/api/joke/list',
        method: 'get',
        params: { num: 10 },
      }).then(res => console.log(res))
    })

    document.querySelector('.btn3').addEventListener('click', function () {
 

      axios({
        url: 'http://ajax-base-api-t.itheima.net/api/login',
        method: 'post',
        data: { username: 'admin', password: '123456' }
      }).then(res => {
        console.log(res);
        alert(res.data.msg)
        location.href = 'https://blog.csdn.net/wusandaofwy?spm=1000.2115.3001.5343'
      })
    })
  </script>
</body>

</html>

axios注意点:

res对象并不是服务器响应的原始数据,而是axios自己额外包的数据

res.config:请求配置

res.data:服务器真正响应的数据

 js中分号作用

    // js中分号作用:语句结束符

        // 如果不加分号,js会往下嗅探

        let res = 1 +

            123

        console.log(res);//124

        💎 自调用函数(立即执行函数)前一定要加分号

        ; (function () {

            console.log('222')

        })()

        💎数组前一定要加分号

        ;[1,2,3,4].join('')

🏆否则都会报错

页面跳转传参

需求:在index页,点击查看详情使用url实现页面跳转传参

实现:

1.在index页给button增加onclick事件挑转到detail页,同时传参数过去

<button class="info" οnclick='location.href="./detail.html?id=${item.id}"'>查看详情</button>

2.在detail页对传入参数处理获取id

 // 🏆 通过对location.search获取参数信息,是一个字符串,对字符串用=进行分割成一个数组,获取数组下标为1的元素就是传过来的id

    let id = location.search.split('=')[1]

3.得到id后通过axios请求数据

 axios({
      url: `https://autumnfish.cn/fruitApi/fruit/${id}`,
      method: 'get',
    }).then(res => {
      const { data: { data } } = res
      console.log(data);
      render(data)
    })

DOM驱动渲染页面

DOM驱动渲染页面是通过document.createElement()创建子元素,然后把子元素插入父元素

父元素.appendChild(子元素)(或者insertBefore(子元素,插入某某元素前))

      let newLi = document.createElement('li')
      newLi.className = 'right_word'
      newLi.innerHTML = `<img src="img/person02.png" />
					<span>${text.value}</span>`
      list.appendChild(newLi)

数据驱动渲染页面

数据驱动渲染页面;

1.声明一个全局数组存贮变量

2,把数据增加进数组(push(),unshift())

3.通过数据的map()和join()方法配合使用,渲染界面

父元素.innerHtml=数组.map(item=>`返回的新数组元素`).join('')

 <script>
    /* 
      使用数据驱动思路
          1.声明一个全局数组存储聊天内容
          2.点击发送
              2.1 非空判断
              2.2 将自己的聊天内容添加到数组中
              2.3 ajax发送请求,获取机器人回复内容添加到数组中
              2.4 文本清空
      */

    let arr = []
    // 文本框
    const text = document.querySelector('.input_txt')
    // 按钮对象
    const sub = document.querySelector('.input_sub')

    sub.addEventListener('click', function () {
      if (!text.value) {
        text.value = ''
        return alert('输入内容不能为空!!!!')
      }
      // 自己写的内容录入数组
      arr.push({
        text: text.value,
        isMe: true
      })
      console.log(arr);
      // 2.4 文本清空
      text.value = ''
      render(arr)
      // 请求机器人
      axios({
        url: 'http://ajax-base-api-t.itheima.net/api/robot',
        method: 'get',
        params: { spoken: text }
      }).then(({ data: { data: { info } } }) => {
        //成功回调
        const txt = info.text
        console.log(txt)
        // 机器人回应文字放入数组
        arr.push({
          text: txt,
          isMe: false,
        })
        console.log(arr)
        render(arr)
      })

    })


    // 封装渲染函数
    function render(data) {
      document.querySelector('.talk_list').innerHTML = data
        .map(item => item.isMe ? `
           <li class="right_word">
            <img src="img/person02.png" />
            <span>${item.text}</span>
          </li> 
          `: `
      <li class="left_word">
            <img src="img/person01.png" />
            <span>${item.text}</span>
          </li> 
          `)
        .join('')
      resetui()
    }

    
  </script>

tab切换

        // 去除active

        document.querySelector('.nav ul li.active').classList.remove('active')

        // 增加active

        item.classList.add('active')

网络请求loading动画

 🏆网络请求loading动画思路

      原理: gif动图

      显示: ajax发送请求之前

      隐藏:  ajax响应之后

      // 💎显示loading动图
      document.querySelector('.cover').style.display = ' block'
      axios({
        url: 'https://autumnfish.cn/api/cq/category',
        method: 'get',
        params: { type }
      }).then(res => {
        //成功回调
        // 💎隐藏loading动图
        document.querySelector('.cover').style.display = ' none'             
        renderData(res.data.data.heros)
      })

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值