AJAX 2——Bootstrap弹框使用、图书管理案例、图片上传方法

AJAX 2------Bootstrap弹框使用、图书管理案例、图片上传方法

1.Bootstrap弹框使用-Modal

  • 通过自定义属性控制

    js 复制代码
    <button  data-bs-toggle="modal" data-bs-target="CSS选择器">点击该按钮显示弹框</button>
     <button data-bs-dismiss="modal" >Close关闭弹框</button>
  • 通过JS控制

    js 复制代码
     //  1. 创建弹框对象
      // 2. 调用弹框对象内置方法
      //   .show() 显示
      //   .hide() 隐藏
      const modalDom = document.querySelector('.name-box')
      const modal = new bootstrap.Modal(modalDom)
      document.querySelector('.edit-btn').addEventListener
          ('click', () => {
            document.querySelector('.username').value = '小小怪'
            modal.show()
        })
     document.querySelector('.save-btn').addEventListener
          ('click', () => {
            const username =  document.querySelector('.username').value
            console.log(username)
            modal.hide()
          })

2.案例:图书管理(增删查改)

  • :注意获取数据渲染列表的时候把图书序号获取过来加到删除编辑模块,是为了后续进行删除编辑可以获取该序号并传给服务器进行操作
js 复制代码
/**
 * 目标1:渲染图书列表
 *  1.1 获取数据
 *  1.2 渲染数据
 */
function getBookList() {
  axios({
    url: 'http://hmajax.itheima.net/api/books',
    params: {
      creator: '老张'
    }
  }).then(result => {
    console.log(result)
    const bookList = result.data.data
    console.log(bookList)
    const htmlStr = bookList.map((item, id) => {
      const { bookname, author, publisher } = item
      return `
      <tr>
          <td>${id + 1}</td>
          <td>${bookname}</td>
          <td>${author}</td>
          <td>${publisher}</td>
          <td data-id=${item.id}>
            <span class="del">删除</span>
            <span class="edit">编辑</span>
          </td>
        </tr>
      `
    }).join('')
    const list = document.querySelector('.list')
    list.innerHTML = htmlStr
  })
}
getBookList()
  • :注意新增完之后要先重置表单,下一次点击新增按钮后表单是空的
js 复制代码
// 目标2:新增图书
const creator = '老张'
const addModalDom = document.querySelector('.add-modal')
const addModal = new bootstrap.Modal(addModalDom)
document.querySelector('.add-btn').addEventListener
  ('click', () => {
    const addForm = document.querySelector('.add-form')
    const bookObj = serialize(addForm, { hash: true, empty: true })
    console.log(bookObj);
    axios({
      url: 'http://hmajax.itheima.net/api/books',
      method: 'post',
      data: {
        ...bookObj,
        creator
      }
    }).then(result => {
      console.log(result)
      getBookList()
      //重置表单
      addForm.reset()
      addModal.hide()
    })
  })
  • :注意使用的请求方法为删除数据,传递参数的方法为地址传参(由接口文档决定的)
js 复制代码
//3.删除列表项
document.querySelector('.list').addEventListener('click', function (e) {
  if (e.target.classList.contains('del')) {
    const delId = e.target.parentNode.dataset.id
    axios({
      url: `http://hmajax.itheima.net/api/books/${delId}`,
      method: 'DELETE',
    }).then(result => {
      console.log(result)
      getBookList()
    })
  }
})
  • :注意编辑的逻辑是:点击编辑按钮获取该图书的唯一序号发送给服务器------>服务器返回图书信息------>将图书信息赋给编辑图书页面的输入框并显示编辑框------>点击保存按钮将修改的信息包括该图书的id传递给服务器,请求方法为修改数据PUT------>渲染页面
js 复制代码
//4.编辑图书
const editModalDom = document.querySelector('.edit-modal')
const editModal = new bootstrap.Modal(editModalDom)
document.querySelector('.list').addEventListener('click', function (e) {
  if (e.target.classList.contains('edit')) {
    const editId = e.target.parentNode.dataset.id
    axios({
      url: `http://hmajax.itheima.net/api/books/${editId}`,
    }).then(result => {
      console.log(result.data.data)
      const bookObj = result.data.data
      //数据对象属性和标签类名一致  防止表单元素过多要一一赋值
      const keys = Object.keys(bookObj)
      keys.forEach(key => {
        document.querySelector(`.edit-form .${key}`).value = bookObj[key]
      })
    })
    editModal.show()
  }
  //4.1编辑 点击保存
})
document.querySelector('.edit-btn').addEventListener('click', function () {
  const editForm = document.querySelector('.edit-form')
  //注意这里的id是从哪里来的呢 这里的hidden隐藏了 前面点击编辑的时候以及从服务器获取火来并赋值到value了
  // <input type="hidden" class="id" name="id" value="509570">
  const { id, bookname, author, publisher } = serialize(editForm, { hash: true, empty: true })
  axios({
    url: `http://hmajax.itheima.net/api/books/${id}`,
    method: 'PUT',
    data: {
      bookname,
      author,
      publisher,
      creator
    }
  }).then(result => {
    console.log(result)
    getBookList()
    editModal.hide()
  })
})

3.案例:图片上传

  • 注意当接口文档标明需要FormData格式上传图片时使用该方法
html 复制代码
<body>
  <!-- 文件选择元素 -->
  <input type="file" class="upload">
  <img src="" alt="" class="my-img">

  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    /**
     * 目标:图片上传,显示到网页上
     *  1. 获取图片文件
     *  2. 使用 FormData 携带图片文件
     *  3. 提交到服务器,获取图片url网址使用
    */
    document.querySelector('.upload').addEventListener('change', e => {
      //获取图片文件
      console.log(e.target.files[0])
      //使用FormData携带图片文件
      const fd = new FormData()
      fd.append('img', e.target.files[0])
      console.log(fd);

      //提交到服务器
      axios({
        url: 'http://hmajax.itheima.net/api/uploadimg',
        method: 'POST',
        data: fd
      }).then(result => {
        console.log(result)
        const imgURL = result.data.data.url
        document.querySelector('.my-img').src = imgURL
      })

    })
  </script>
</body>
相关推荐
Zheng11312 小时前
【可视化大屏】将柱状图引入到html页面中
javascript·ajax·html
wclass-zhengge13 小时前
Redis篇(最佳实践)(持续更新迭代)
redis·缓存·bootstrap
前端李易安13 小时前
ajax的原理,使用场景以及如何实现
前端·ajax·okhttp
Code成立13 小时前
1、深入理解Redis线程模型
数据库·redis·bootstrap
萧鼎1 天前
Python常见问题解答:从基础到进阶
开发语言·python·ajax
儒雅的烤地瓜1 天前
JS | 如何解决ajax无法后退的问题?
前端·javascript·ajax·pushstate·popstate事件·replacestate
洛文泽2 天前
application.yml和bootstrap.yml
java·spring boot·bootstrap·html
学习使我快乐012 天前
AJAX 1——axios体验、认识URL、常用请求方法、HTTP协议、错误处理、form-serialize插件
前端·http·ajax·okhttp·axios
帅次2 天前
解决 Android WebView 无法加载 H5 页面常见问题的实用指南
android·okhttp·gradle·binder·webview·retrofit·appcompat