ajax初学第一步

这篇博客详细介绍了如何开始使用ajax工具库axios,包括引入axios、基本请求结构、参数传递、各种请求方法的使用,如GET、POST、DELETE,并通过实际案例展示了用户登录、表单提交、头像上传等应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.学会引入工具库  axios

2.结构 axios({

url:'根据接口文档',

method:'GET' (是获取),'POST'增加 ,'DELETE'删除

params:是get的对象参数 post delete是data

形参根据接口文档

}).then(res =>{

})

  <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script> 
    <!-- 1.引入工具库 axios js工具 -->
</head>
<body>
    <script>
      axios({
        // url:'http://ajax-api.itheima.net/api/province',
        url:'http://hmajax.itheima.net/api/area',
        method:'GET',
        params: {
            pname:'浙江省',
            cname:'杭州市'
        }
      }).then(res => {
        console.log(encodeURI(res));
        console.log(decodeURI(res));
      })
    </script>

2.传参本质和url编码

encoudeURI和decodeURI

<script>
       

          const str = '你是蔡徐坤'
          console.log(encodeURI(str)); // 转换成乱码
          console.log(decodeURI(str)); // 把乱码转换成中文
    </script>

3.案例

 <script>
      axios({
        url:'http://hmajax.itheima.net/api/news',
        method:'GET'
      }).then(res => {
        console.log(res);
        const arr = res.data.data
       document.querySelector('#news-list').innerHTML = arr.map(item =>{ 
         const {img, title, source,cmtcount} = item
        return `
        <div class="news-item">
        <img class="thumb" src="${item.img}" alt="" />
        <div class="right-box">
          <!-- 新闻标题 -->
          <h1 class="title">${item.title}</h1>
          <div class="footer">
            <div>
              <!-- 新闻来源 -->
              <span>${item.source}</span>&nbsp;&nbsp;
              <!-- 发布日期 -->
              <span>2019-10-28 10:14:38</span>
            </div>
            <!-- 评论数量 -->
            <span>评论数:${item.cmtcount}</span>
          </div></div>
      </div>`
        
       }).join('')
      })

4.axios的增和查

 <script>
        // axios 新增数据 用method 'POST' 参数名:data
        axios({
            url:'http://hmajax.itheima.net/api/books',
            method:'POST',
            data:{
                bookname:'钢铁如何炼成鸡的',
                author: '蔡徐坤',
                publisher: '北京出版社',
                creater: '保尔'
            }
        }).then(res => {
            console.log(res);
        })

        axios({
            url:'http://hmajax.itheima.net/api/books',
            method:'GET',
            params:{
                creater:'保尔'
            }
        }).then(res => {
            console.log(res);
        })
     </script>

5.用户登录案例

<style>
    html,
    body {
      background-color: #f8f8f8;
    }

    .login-box {
      width: 400px;
      position: fixed;
      top: 20%;
      left: 50%;
      transform: translateX(-50%);
      border: 1px solid #efefef;
      padding: 20px;
      border-radius: 4px;
      box-shadow: 1px 1px 5px #cfcfcf;
      background-color: #fff;
      transition: box-shadow 0.3s ease;
    }

    .login-box:hover {
      transition: box-shadow 0.3s ease;
      box-shadow: 1px 1px 20px #cfcfcf;
    }
  </style>
</head>

<body>
  <div class="login-box">
    <div class="form-group">
      <label for="username">Account</label>
      <!-- 账号 -->
      <input type="text" class="form-control" id="username" autocomplete="off">
      <small id="emailHelp" class="form-text text-muted">
        The available account is<strong>admin</strong>
      </small>
    </div>
    <div class="form-group">
      <!-- 密码 -->
      <label for="password">Password</label>
      <input type="password" class="form-control" id="password">
      <small id="emailHelp" class="form-text text-muted">The available password is
        <strong>123456</strong></small>

    </div>
    <button type="submit" class="btn btn-primary" id="btnLogin">Submit</button>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>

  <script>
      const btn = document.querySelector('#btnLogin')
      btn.addEventListener('click',() => {
        const username = document.querySelector('#username').value.trim()
        const password = document.querySelector('#password').value.trim()
        axios({
            url:'http://ajax-api.itheima.net/api/login',
            method:'POST',
            data:{
            username: username,
            password: password
            }
        }).then(res =>{
            alert('登录成功')
            console.log(res);
        }).catch(err => {
            alert('登录失败')
            console.log(err);
        })
      })
  </script>

6.表单提交利用serialize

 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        html,
        body {
            background-color: #f8f8f8;
        }

        .login-box {
            width: 400px;
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translateX(-50%);
            border: 1px solid #efefef;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 1px 1px 5px #cfcfcf;
            background-color: #fff;
            transition: box-shadow 0.3s ease;
        }

        .login-box:hover {
            transition: box-shadow 0.3s ease;
            box-shadow: 1px 1px 20px #cfcfcf;
        }
    </style>
</head>

<body>
    <div class="login-box">
        <form id="myForm">
            <div class="form-group">
                <label for="username">Account</label>
                <!-- 账号 -->
                <input type="text" class="form-control" name="username" id="username" autocomplete="off">
                <small id="emailHelp" class="form-text text-muted">The available account is
                    <strong>admin</strong></small>
            </div>
            <div class="form-group">
                <!-- 密码 -->
                <label for="password">Password</label>
                <input type="password" class="form-control" name="password" id="password">
                <small id="emailHelp" class="form-text text-muted">The available password is
                    <strong>123456</strong></small>
            </div>
            <button type="submit" class="btn btn-primary" id="btnLogin">Submit</button>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script src="./form-serialize.js"></script>
    <script>
        // 1.获取按钮注册点击事件
         const btn = document.querySelector('#btnLogin')
         btn.addEventListener('click', e => {
             e.preventDefault()
          const p = serialize(document.querySelector('#myForm'),{ hash: true})
          console.log(p);
          axios({
            url:'http://ajax-api.itheima.net/api/login',
            method:'POST',
            data: p
          }).then(res => {
            console.log(res);
          }).catch(err => {
           alert('失败')  
         })
         })
    </script>

7.头像上传案例

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        .thumb-box {
            text-align: center;
            margin-top: 50px;
        }

        .thumb {
            width: 250px;
            height: 250px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid black !important;
        }
    </style>
</head>

<body>
    <div class="thumb-box">
        <!-- 头像 -->
        <img  class="img-thumbnail thumb" src="./lib/images/cover.jpg" id="img">
        <div class="mt-2">
            <!-- 文件选择框(因为无法改样式, 所以css隐藏, 但是还可以用js获取) -->
            <input style="display: none;" type="file" id="iptFile" accept="image/*">
            <button id="btn">选择头像</button>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script>
           // 创建按钮隐藏文件上传视口  
          document.querySelector('#btn').addEventListener('click',() => {
            // 模拟点击事件
             document.querySelector('#iptFile').click()
          })


        document.querySelector('#iptFile').addEventListener('change',(e) => {
            console.log(e.target.files);
           if(e.target.files.length == 0) {
            return
           }
           const file = e.target.files[0]
           console.log('上传文件',file);
          // 上传文件 用formData
            const fd = new FormData()
            fd.append('avatar',file)  // 添加参数 和类型
            // 通过ajax获取数据
            axios({
                url:'http://hmajax.itheima.net/api/file',
                method: 'POST',
                data: fd
            }).then(res =>{
                console.log(res.data.data.url);
                document.querySelector('#img').src = res.data.data.url
            })
        })

8.图书管理案例

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        :root {
            font-size: 15px;
        }

        body {
            padding-top: 15px;
        }
    </style>
</head>

<body >
    <!-- 栅格系统 -->
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <h1>图书管理</h1>
            <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addModal" id="myAddBtn">添加</button>
        </div>
        <table  class="table table-bordered table-striped table-dark table-hover text-center">
            <thead>
                <!-- 表头行 -->
                <tr>
                    <th scope="col">Id</th>
                    <th scope="col">书名</th>
                    <th scope="col">作者</th>
                    <th scope="col">出版社</th>
                    <th scope="col">操作</th>
                </tr>
            </thead>
            <tbody id="tbody">
                <!-- 表格中的每一行 -->
                <tr>
                    <th scope="row">xxx</th>
                    <td>xxx</td>
                    <td>xxx</td>
                    <td>xxx</td>
                    <td>
                        <button type="button" class="btn btn-link btn-sm btn-delete">删除</button>
                        <button type="button" class="btn btn-link btn-sm btn-update">编辑</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <!-- add Modal -->
    <div class="modal fade" id="addModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加图书</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addForm" class="p-3">
                        <!-- 书名 -->
                        <div class="mb-3">
                            <label class="form-label">书名</label>
                            <input type="text" name="bookname" class="form-control" placeholder="请输入图书名称"
                                name="bookname" />
                        </div>
                        <!-- 作者 -->
                        <div class="mb-3">
                            <label class="form-label">作者</label>
                            <input type="text" name="author" class="form-control" placeholder="请输入作者名字" name="author" />
                        </div>
                        <!-- 出版社 -->
                        <div class="mb-3">
                            <label class="form-label">出版社</label>
                            <input type="text" name="publisher" class="form-control" placeholder="请输入出版社名称"
                                name="publisher" />
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="addBtn">确认</button>
                </div>
            </div>
        </div>
    </div>
    <!-- edit Modal -->
    <div class="modal fade" id="editModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑图书</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editForm" class="p-3">
                        <input type="hidden" name="id" />
                        <!-- 书名 -->
                        <div class="mb-3">
                            <label class="form-label">书名</label>
                            <input type="text" name="bookname" class="form-control" placeholder="请输入图书名称"
                                name="bookname" />
                        </div>
                        <!-- 作者 -->
                        <div class="mb-3">
                            <label class="form-label">作者</label>
                            <input type="text" name="author" class="form-control" placeholder="请输入作者名字" name="author" />
                        </div>
                        <!-- 出版社 -->
                        <div class="mb-3">
                            <label class="form-label">出版社</label>
                            <input type="text" name="publisher" class="form-control" placeholder="请输入出版社名称"
                                name="publisher" />
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="editBtn">确认</button>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
    <script src="./lib/form-serialize.js"></script>
    <script>
        function render () {

            axios({
             url:'http://hmajax.itheima.net/api/books',
             method:'GET',
 
            }).then(res => {
              console.log(res.data.data);
              const arr = res.data.data
              let str = arr.map(item => {
                 return `
                 <tr>
                     <th scope="row">${item.id}</th>
                     <td>${item.bookname}</td>
                     <td>${item.creator}</td>
                     <td>${item.publisher}</td>
                     <td>
                         <button data-id = '${item.id}'type="button" class="btn btn-link btn-sm btn-delete">删除</button>
                         <button type="button" class="btn btn-link btn-sm btn-update">编辑</button>
                     </td>
                 </tr>`
                  // 索引号得用引号包起来
              }).join('')
              document.querySelector('#tbody').innerHTML= str
            })
        }
            render()
             // 图书管理删除
           //2.1创建事件委托 利用时间冒泡机制
           document.querySelector('#tbody').addEventListener('click',(e) =>{
            // 判断点击的是否是button按钮
            if(e.target.tagName === 'BUTTON') {
                // 创建自定义属性,这样点击删除指定的数据显示显示删除哪本书的id
                const id = e.target.dataset.id
                console.log(id);
                axios({
                    url:'http://hmajax.itheima.net/api/books/'+id,
                    method:'DELETE',
                    data:id
                }).then(res =>{
                    console.log(res);
                    render()
                })
            }
           })
    </script>

9机器人对答案例

<link rel="stylesheet" href="https://unpkg.com/reset.css@2.0.2/reset.css" />
  <style>
    body {
      margin: 0;
      font-family: 'Microsoft YaHei', sans-serif;
    }

    .wrap {
      position: absolute;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }

    .header {
      height: 55px;
      background: linear-gradient(90deg, rgba(246, 60, 47, 0.6), rgba(128, 58, 242, 0.6));
      overflow: hidden;
    }

    .header h3 {
      color: #faf3fc;
      line-height: 55px;
      font-weight: normal;
      float: left;
      letter-spacing: 2px;
      margin-left: 25px;
      font-size: 18px;
      text-shadow: 0px 0px 5px #944846;
    }

    .header img {
      float: right;
      margin: 7px 25px 0 0;
      border-radius: 20px;
      box-shadow: 0 0 5px #f7f2fe;
    }

    .main {
      position: absolute;
      left: 0;
      right: 0;
      top: 55px;
      bottom: 55px;
      background-color: #f4f3f3;
      box-sizing: border-box;
      overflow: hidden;
    }

    .talk_list {
      width: 100%;
      height: 100%;
      overflow-y: auto;
    }

    .talk_list li {
      overflow: hidden;
      margin: 20px 0px 30px;
      display: flex;
    }

    .talk_list .left_word {
      justify-content: flex-start;
    }

    .talk_list .left_word img {
      margin-left: 20px;
      width: 44px;
      height: 44px;
    }

    .talk_list .left_word span {
      background-color: #fe9697;
      padding: 10px 15px;
      border-radius: 12px;
      font-size: 16px;
      color: #fff;
      margin-left: 15px;
      margin-right: 20px;
      position: relative;
      line-height: 24px;
    }

    .talk_list .left_word span:before {
      content: '';
      position: absolute;
      left: -8px;
      top: 12px;
      width: 13px;
      height: 12px;
      background: url('../img/corner01.png') no-repeat;
    }

    .talk_list .right_word {
      justify-content: flex-end;
    }

    .talk_list .right_word img {
      margin-right: 20px;
      width: 44px;
      height: 44px;
    }

    .talk_list .right_word span {
      background-color: #fff;
      padding: 10px 15px;
      border-radius: 12px;
      font-size: 16px;
      color: #000;
      margin-right: 15px;
      margin-left: 20px;
      position: relative;
      line-height: 24px;
    }

    .talk_list .right_word span:before {
      content: '';
      position: absolute;
      right: -8px;
      top: 12px;
      width: 13px;
      height: 12px;
      background: url('../img/corner02.png') no-repeat;
    }

    .footer {
      width: 100%;
      height: 55px;
      left: 0px;
      bottom: 0px;
      background-color: #fff;
      position: absolute;
      display: flex;
      align-items: center;
      padding: 0 10px;
      box-sizing: border-box;
    }

    .input_txt {
      height: 37px;
      border: 0px;
      background-color: #f4f3f3;
      border-radius: 8px;
      padding: 0px;
      margin: 0 10px;
      outline: none;
      text-indent: 15px;
      flex: 1;
    }

    .input_sub {
      width: 70px;
      height: 37px;
      border: 0px;
      background-color: #fe9697;
      margin: 0;
      border-radius: 8px;
      padding: 0px;
      outline: none;
      color: #fff;
      cursor: pointer;
    }
  </style>

</head>

<body>
  <div class="wrap">
    <!-- 头部 Header 区域 -->
    <div class="header">
      <h3>小思同学</h3>
      <img src="lib/img/person01.png" alt="icon" />
    </div>
    <!-- 中间 聊天内容区域 -->
    <div class="main">
      <ul class="talk_list" style="top: 0px;" id="talk_list">
        <!-- 机器人 -->
        <li class="left_word">
          <img src="lib/img/person01.png" /> <span>嗨,最近想我没有?</span>
        </li>
        <!-- 我 -->
        <li class="right_word">
          <img src="lib/img/person02.png" /> <span>想,想你教我写代码!</span>
        </li>
      </ul>
    </div>
    <!-- 底部 消息编辑区域 -->
    <div class="footer">
      <img src="lib/img/person02.png" alt="icon" />
      <input type="text" placeholder="说的什么吧..." class="input_txt" id="ipt" />
      <input type="button" value="发 送" class="input_sub" id="btnSend" />
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
  <script>
    // 目标: 完成和机器人聊天效果
    const talk_list = document.querySelector('#talk_list')
   
    document.querySelector('#btnSend').addEventListener('click',() =>{
        const word  = document.querySelector('#ipt').value
        const li = document.createElement('li')
         li.className =' right_word'
         li.innerHTML = ` <img src="lib/img/person02.png" /> <span>${word}</span>`
         talk_list.appendChild(li)
         talk_list.scrollTop = talk_list.scrollHeight   
        //alert(1)
            axios({
                url:'http://ajax-base-api-t.itheima.net/api/robot',
                method: 'GET',
                params: {
                spoken:word
                }
            }).then(res =>{
                console.log(res.data.data.info.text);
                let text = res.data.data.info.text
                const li = document.createElement('li')
                li.className =' left_word'
                li.innerHTML = ` <img src="lib/img/person01.png" /> <span>${text}</span>`
                talk_list.appendChild(li)
            })
            })
  </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值