自己封装一个ajax 图片上传 还需多多请教各位大佬多多指教

62 阅读2分钟

自己封装一个ajax

记得是common.js文件

// 公共的js: common.js tools.js  public.js
// 封装一个方法 链有很多的属性,控制ajax的发送和接受
// itcast({
//   method: '',//类比 axios中的menthod
//   url: '',   //类比 axios中的url
//   params: {}, //类比 axios中的params
//   data: {}, //类比axios中的data
//   success:function(res){} //success是结束响应的处理函数 类比then(res)
// })



// 封装一个方法 队形转换为字符串
//  {a:1,b:2,c:3}" => a=1&b=2&c=3  
function objectTostrig(obj) {
  // 思路:属性值和值 链接为a=1类型,添加到数组中,最后用&链接在一起
  let arr = []
  for(let k in obj){
    // k属性 obj[k]值 a=1 添加到数组中
    arr.push(`${k}=${obj[k]}`)
  }
  // 循环完毕后
  return arr.join('&')
}


// 封装函数,需要处理参数,有且只有一个参数.参数最起码要有五个属性
// menthod 请求方式 url资源路径 params查询参数
// data 请求体参数 succesd 接受数据回调函数
function itcast(config) {
  // 1创建xml实列
  let xhr = new XMLHttpRequest()
    // 4接收
  xhr.onload = function () {
    // Josn类型字符串,转换为对象类型,称为反序列化
   
    let obj = JSON.parse(xhr.response)
    // obj就是接受到响应数据 config.success就是要处理这个数据函数
    config.success(obj)
  }
  // 判断请求方式
  if (config.method.toUpperCase()=='GET') {
      // 判断参数类型 :"a=1&b=2$=3   {a:1,b:2,c:3}" 
    if (typeof config.params=='string') {
        // 2设置 请求方式,资源路径
      xhr.open('GET',config.url+'?'+config.params)
        // 3发送
         xhr.send()
    } else if (typeof config.params=='object') {
      xhr.open('GET', config.url + '?' + objectTostrig(config.params))   
      xhr.send()
    } else if (typeof config.params=='undefined') {
      xhr.open('GET', config.url)
      xhr.send()
    }
  } else if (config.method.toUpperCase()=='POST') {
     // 2设置 请求方式,资源路径
    // 判断请求体参数 a=1&b=2&c=3    {a:1,b:2,c:3}
    if (typeof config.data == "string") {
      // 设置请求头
      xhr.open('POST', config.url)
           xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      // 3发送
      xhr.send(config.data)
    } else if (typeof config.data == "object") {
      xhr.open('POST', config.url)
      xhr.setRequestHeader('Content-Type','application/json')
      // 3发送 -序列化,转换为Json类型的字符串
      xhr.send(JSON.stringify(config.data))
    }
  }

}
  </script>
</body>
</html>

测试html文件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <!-- 引入自己的common.js -->\
  <script src="./common.js"></script>
  <script>
    //  1get
    itcast({
      method:'get',
      url:'http://www.liulongbin.top:3009/api/getbooks',
      // 传递参数
      // params:"id=2&bookname=西游记",
      params:{id:2,bookname:'西游记'},
      success:function(res){
        console.log(res)
      }
    })
    // 2post
    itcast({
      method:'post',
      url:'http://www.liulongbin.top:3009/api/addbook',
      // 传递参数
      // data:'bookname=四题&author=大傻逼&publisher=上海三十',
       data:{bookname:"三体四",author:"大飞",publisher:"上海出版社"},
       success:function(res){
          console.log(res)
       }
    })
  </script>
</body>
</html>

图片上传

 <style>
    .thumb-box {
      text-align: center;
      margin-top: 50px;
    }

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

<body>
  <div class="thumb-box">
    <!-- 头像 -->
    <img src="./images/cover.jpg" class="img-thumbnail thumb" alt="">
    <div class="mt-2">
      <!-- 文件选择框 -->
      <!-- accept 属性表示可选择的文件类型 -->
      <!-- image/* 表示只允许选择图片类型的文件 -->
      <input multiple type="file" id="iptFile" accept="image/*" style="display: none;">
      <!-- 选择头像图片的按钮 -->
      <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
    </div>
  </div>

  <script src="./lib/jquery-v3.6.0.js"></script>
  <script src="./lib/axios.js"></script>

 let inp=document.querySelector('input')
    let btn=document.querySelector("button")
    let img=document.querySelector('img')
    btn.onclick=function(){
      // 是通过dom对象直接调用的,不要再前面加on
      // 不是所有的事件都能直接调用:mouseover mouseemner
      // 能够直接调用的:click() focus() reset()
      inp.click()
      // 2选择图片后,发送ajax 选择图片触发change事件 
      inp.onchange=function(){
        // 获取文件对象 -input,files是一个文件组成的伪数组
       let file= this.files[0];//input的type值等于file的dom对象,上面才有这个属性
        // 判断,如果内容为undefinde,给出提示
        // console.log(file)
        // if(file==undefined){
        //       return alert('请选择上传文件!')
        // }
        // 基于文件对象formData对象
        let fd= new FormData
        //把文件对象,放入formdata对象中,属性以接口文档为准
        fd.append('avatar',file)
        console.log(...fd)
        // 发送axios
        axios({
          url:'http://www.liulongbin.top:3009/api/upload/avatar',
          method:'post',
          // 传递参数,不要再fd对象外面再套{}
          data:fd
        }).then(({data:res})=>{
          //判断验证码
          // console.log(res)
          if(res.code!=200){
            return alert(res.message)
          }
          // 异步代码后执行
          // 成功后提示,修改图片路径
          alert("恭喜您,上传头像成功");
          img.src='http://www.liulongbin.top:3009'+res.url;
        })
      }
    }