AJAX案例

案例一:个人信息案例

目标分析:

信息渲染

const creator = '老唐'
axios({
  url: 'http://hmajax.itheima.net/api/settings',
  params: {
    creator
  }
}).then(result => {
  const userObj = result.data.data
  Object.keys(userObj).forEach(key => {
    if (key === 'avatar') {
      //赋予默认头像
      document.querySelector('.prew').src = userObj[key]
    }
    else if (key === 'gender') {
      const gRadioList = document.querySelectorAll('.gender')
      const gNum = userObj[key]
      gRadioList[gNum].checked = true
    } else {
      document.querySelector(`.${key}`).value = userObj[key]
    }
  })
})

修改头像

const fd = new FormDate()

fd.append('avatar',e.target.files[0])

document.querySelector('.upload').addEventListener('change', e => {
  const fd = new FormData()
  fd.append('avatar', e.target.files[0])
  fd.append('creator', creator)
  axios({
    url: 'http://hmajax.itheima.net/api/avatar',
    //采用put格式
    method: 'PUT',
    data: fd
  }).then(result => {
    const imgUrl = result.data.data.avatar
    document.querySelector('.prew').src = imgUrl
  })
})

提交表单

toast是一种小的通知消息框,可以用来向用户显示简短的反馈信息。

const userForm = document.querySelector('.user-form')

const userObj = serialize(userForm, { hash: true, empty: true })

//提交表单
document.querySelector('.submit').addEventListener('click', () => {
  const userForm = document.querySelector('.user-form')
  const userObj = serialize(userForm, { hash: true, empty: true })
  userObj.creator = creator
  //转换成数字格式
  userObj.gender = +userObj.gender
  axios({
    url: 'http://hmajax.itheima.net/api/settings',
    method: 'PUT',
    data: userObj
  }).then(result => {
    const toastDom = document.querySelector('.my-toast')
    const toast = new bootstrap.Toast(toastDom)
    toast.show()
  })
})

案例二:图书处理

目标:

渲染图书列表

const creator = '老唐'
function getBooksList() {
  axios({
    url: 'http://hmajax.itheima.net/api/books',
    params: {
      // 外号:获取对应数据
      creator
    }
  }).then(result => {
    console.log(result.data.data)
    const bookList = result.data.data
    const htmlStr = bookList.map((item, index) => {
      return `
      <tr>
          <td>${index + 1}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td data-id=${item.id}>
            <span class="del">删除</span>
            <span class="edit">编辑</span>
          </td>
        </tr>
      `
    }).join('')
    document.querySelector('.list').innerHTML = htmlStr
  })
}
//网页加载运行,获取并渲染列表一次
getBooksList()

增加图书

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 })
  axios({
    url: 'http://hmajax.itheima.net/api/books',
    method: 'post',
    data: {
      //得到所有的元素
      ...bookObj,
      creator
    }
  }).then(result => {
    console.log(result)
    getBooksList()
    //重置表单
    addForm.reset()
    //隐藏表单
    addModal.hide()
  })
})

删除图书

//删除图书
document.querySelector('.list').addEventListener('click', (e) => {
  if (e.target.classList.contains('del')) {
    const theId = e.target.parentNode.dataset.id
    axios({
      url: `http://hmajax.itheima.net/api/books/${theId}`,
      method: 'DELETE'
    }).then(result => {
      getBooksList()
    })
  }
})

编辑图书

const editDom = document.querySelector('.edit-modal')
const editModal = new bootstrap.Modal(editDom)
document.querySelector('.list').addEventListener('click', e => {
  if (e.target.classList.contains('edit')) {
    const theId = e.target.parentNode.dataset.id
    axios({
      url: `http://hmajax.itheima.net/api/books/${theId}`,
    }).then(result => {
      const bookObj = result.data.data
      const keys = Object.keys(bookObj)
      keys.forEach(key => {
        document.querySelector(`.edit-form .${key}`).value = bookObj[key]
      })
    })
    editModal.show()
  }
})
document.querySelector('.edit-btn').addEventListener('click', () => {
  const editForm = document.querySelector('.edit-form')
  const { id, author, publisher, bookname } = serialize(editForm, { hash: true, empty: true })
  axios({
    url: `http://hmajax.itheima.net/api/books/${id}`,
    method: 'PUT',
    data: {
      bookname,
      author,
      publisher,
      creator
    }
  }).then(() => {
    getBooksList()
  })
  edit

案例三:学习反馈


考察回调函数嵌套问题,async await 

省市区下拉列表切换

省级列表

axios({
  url: 'http://hmajax.itheima.net/api/province',
}).then(result => {
  const optionStr = result.data.list.map(pname => `<option value="${pname}">${pname}</option>`
  ).join('')
  document.querySelector('.province').innerHTML = `<option value="">省份</option>` + optionStr
})

市级列表

当省级列表发生改变时触发调用e.target.value

document.querySelector('.province').addEventListener('change', async e => {
  console.log(e.target.value)
  const result = await axios({
    url: 'http://hmajax.itheima.net/api/city',
    params: {
      pname: e.target.value
    }
  })
  const optionStr = result.data.list.map(cname => `<option value="${cname}">${cname}</option>`).join('')
  document.querySelector('.city').innerHTML = `<option value="">城市</option>` + optionStr
  //清空地区数据
  document.querySelector('.area').innerHTML = `<option value="">地区</option>`
})

城市列表

document.querySelector('.city').addEventListener('change', async e => {
  const result = await axios({
    url: 'http://hmajax.itheima.net/api/area',
    params: {
      pname: document.querySelector('.province').value,
      cname: e.target.value
    }
  })
  const optionStr = result.data.list.map(areaName => `<option value="${areaName}">${areaName}</option>`).join('')
  document.querySelector('.area').innerHTML = `<option value="">地区</option>` + optionStr
})

数据提交

document.querySelector('.submit').addEventListener('click', async () => {
  const form = document.querySelector('.info-form')
  //获得表格数据
  const data = serialize(form, { hash: true, empty: true })
  console.log(data)
  try {
    const result = await axios({
      url: 'http://hmajax.itheima.net/api/feedback',
      method: 'POST',
      data
    })
    console.log(result)
    alert(result.data.message)
  } catch (error) {
    console.dir(error)
    //返回错误信息
    alert(error.response.data.message)
  }
})

案例四:商品分类

二级分类

axios({
      url: 'http://hmajax.itheima.net/api/category/top'
    }).then(result => {
      const secPromiseList = result.data.data.map(item => {
        return axios({
          url: 'http://hmajax.itheima.net/api/category/sub',
          params: {
            id: item.id
          }
        })
      })
      const p = Promise.all(secPromiseList)
      p.then(result => {
        console.log(result)
        //渲染界面
        const htmlStr = result.map(item => {
          const dataObj = item.data.data
          return `
          <div class="item">
          <h3>${dataObj.name}</h3>
          <ul>
            ${dataObj.children.map(item => {
            return `<li>
              <a href="javascript:;">
              <img src="${item.picture}">
              <p>${item.name}</p>
              </a>
               </li>`
          }).join('')}
        </ul>
      </div>
          `
        }).join('')
        console.log(htmlStr)
        document.querySelector('.sub-list').innerHTML = htmlStr
      })
    })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值