Ajax

130 阅读3分钟

Ajax

ajax的 5种方式

请求方式 和 携带参数写法

1 get 和 delete    params 上携带参数
2 post put patch   data 

新增 数据:POST

// post 简写   
    // axios.post('url',{参数对象})
    axios.post('http://www.itcbc.com:3006/api/addbook', {
      bookname: 'post 简写',
      author: '我自己',
      publisher: '黑马出版社',
      appkey: 'abc123abc',
    }).then((result) => {
      console.log(result)
    })
 // 要配合 data 使用
<script>
    axios({
      url:'http://www.itcbc.com:3006/api/addbook',
      method:'POST',
      data:{
        bookname:'在学前端的靓仔',
        author:'太难了是吗,不是的',
        publisher:'广州出版社',
        appkey:'abc123abc',
      },
    }).then(result => {
      console.log(result);
    })
  </script>

获取 数据:GET

// get 请求的简写方式 1
  axios.get('http://www.itcbc.com:3006/api/getbooks').then((result) => {
      console.log(result);
    })


// get 请求的简写方式 2   携带参数  把正确的写法 存一份  笔记!! 
axios.get('http://www.itcbc.com:3006/api/getbooks',{params:{appkey:'abc123abc'}}).then((result) => {
      console.log(result);
    })
// 方法 1
axios({
      //  请求参数  英文的符号为分割
      //  ?  前面部分是正常的url
      // ? 后面的参数部分用&连接起来   a=1&b=2
      url: 'http://www.itcbc.com:3006/api/getbooks?bookname=斗破苍穹&author=我自己',
      method: 'GET'
    }).then((result) => {
      console.log(result);
    })

// 方法 2   params 携带参数
 axios({
      url: 'http://www.itcbc.com:3006/api/getbooks',
      method: 'GET',
      // 2 在params 对象中携带  本质 也是 帮我们将对象 转成了字符串 然后拼接在 url上 
      'params': {
        bookname: '云边的小卖部',
        appkey: 'abc123abc',
      }

    }).then(result => {
      console.log(result);
    })

删除 数据:DELETE

// 判断 用户 点击 删除还是取消
// confirm 是一个弹窗 点击确认返回的是 true ,点击取消返回 false
        if (confirm('确实要删除吗')) {   
          axios({
            url: 'http://www.itcbc.com:3006/api/delbook',
            method: 'DELETE',
            params: {
              appkey: 'abc123abc',
              id: e.target.dataset.id
            }
          }).then((result) => {
            render()
            console.log('是的');
          })
        } else {
          console.log('不是的');
        }

完整 更新 :PUT

部分 更新 :PATCH

快速获取 form表单值

JQ 方法

<!-- 引入 jq 文件 -->
  <script src="./lib/jquery.js"></script>
  <script>
    // 获取 form 表单
    const form = document.querySelector('form')
    // submit 用来提交表单
    form.addEventListener('submit',function(event){
      // 阻止默认行为
      event.preventDefault()
      // 接收 JQ 获取过来的数据
      const query = $('form').serialize()
      console.log(query);
    })
  </script>

JS 原生方式

    // 1 快速把form标签中的表单 获取到 存在 formdata对象中
      const fd = new FormData(this)

      // 2 把formdata中的表单数据 存在  usp对象
      const usp = new URLSearchParams(fd)

      // 3 usp对象 有一个方法 专门把数据转成 字符串参数形式  toString()
      const query = usp.toString()  
      'query 只是一个变量名,要配合实际起名 




    <form class="forms">
        <input class="plac1" type="text" placeholder="书籍的名称" name="bookname">
        <input class="plac2" type="text" placeholder="作者" name="author">
        <input class="plac3" type="text" placeholder="出版社" name="publisher">
        <button id="addButton">新增书籍</button>
    </form>

    const forms = document.querySelector('.forms')
    forms.addEventListener('submit', function (e) {
   // 阻止 默认行为
      e.preventDefault()
        
        </ 需要配合 input 的 name 属性名一起使用,文档要求是什么参数名就要对应是什么参数名
    // 以下三老表  是固定搭配   
      const fd = new FormData(this)
      fd.append('appkey','abc123abc')     'appkey 在下面无法传入,所以要先添加进去'
      const usp = new URLSearchParams(fd)
      const data = usp.toString()    'post 方式是配合 data 使用' 'get 方式就要配合 params'
      
      axios.post('http://www.itcbc.com:3006/api/addbook',data).then((result) => {
        fn()
      })
    })

原生封装


    // 封装起来,下次用直接调用   传 form 表单用即可
    function toQuery(form) {
      const fd = new FormData(form)
      const usp = new URLSearchParams(fd)
      const query = usp.toString()   
      return query
    }

FormData 文件上传 服务器

<input type="file" name="" id="" />
    <img src="" alt="" />
    <script src="./lib/axios.js"></script>
    <script>
      const input = document.querySelector('input');
      const img = document.querySelector('img');
      input.addEventListener('change', function () {
        const url = URL.createObjectURL(this.files[0]);
        img.src = url;

        // 使用formData来包装数据
        const fd = new FormData();
        // 添加数据
        // fd.append("avatar",文件)
        fd.append('avatar', this.files[0]);

        // 请求三大关键
        // url  method  data
        // axios.post("http://www.itcbc.com:3006/api/formdata",{a:1,b:2})
        axios
          .post('http://www.itcbc.com:3006/api/formdata', fd)
          .then((result) => {
            console.log(result);
          });
      });
    </script>

照片加载本地

<body>
  <input type="file">
  <img src="" alt="">
  <script>
    const input = document.querySelector('input')
    const img = document.querySelector('img')

    input.addEventListener('change', function () {

         // files属性查看文件
        console.log(this.files);
      // this.files 返回的是一个数组,如果要拿每一项就要遍历
	  // this 指向input  .files获取文件

        
      // 获取到图片在内存中的地址
      // URL.createObjectURL(你想要获取谁的内存地址)  返回 内存中的 文件地址
      const url = URL.createObjectURL(this.files[0])

      // 把内存中的图片 的地址 设置给 真正的图片标签
      img.src = url
    })
  </script>
</body>

照片上传到服务器

<body>
  <input type="file" name="" id="" />
  <img src="" alt="" />
  <script src="./lib/axios.js"></script>
  <script>
    const input = document.querySelector('input');
    const img = document.querySelector('img');
    input.addEventListener('change', function () {

      // 获取到图片在内存中的地址
      // URL.createObjectURL(你想要获取谁的内存地址)  返回 内存中的 文件地址
      const url = URL.createObjectURL(this.files[0]);
      img.src = url;

      // 使用formData来包装数据
      const fd = new FormData();
      // 添加数据
      // fd.append("avatar",文件)
      fd.append('avatar', this.files[0]);

      // 请求三大关键
      // url  method  data
      // axios.post("http://www.itcbc.com:3006/api/formdata",{a:1,b:2})

      // 简写方式
      axios
        .post('http://www.itcbc.com:3006/api/formdata', fd)
        .then((result) => {
          // 返回上传 后的网址,有网都可以查看
          console.log(result.data.data);
        });
    });
  </script>
</body>

axios 基地址

// 基地址
axios.defaults.baseURL = 'http://www.itcbc.com:3006';

axios({
  url: '/api/getbooks',
  method: 'GET',
})

XMLHttpRequest

1-4个关键步骤


 <script>
    // 1 创建 xhr 实例
    const xhr = new XMLHttpRequest()

    // 2 调用open方法 (指定请求的类型、指定请求的url)
    xhr.open('GET', 'http://www.itcbc.com:3006/api/getbooks')

    // 3 开始发起请求
    xhr.send()

    // 4 监听 数据响应
    xhr.addEventListener('load', function () {
      // 获取响应结果
      // 本质上返回字符串类型是正确的
      // axios别人封装的库, 别人帮我们重新把 JSON字符串 转成了对象而已
      console.log(JSON.parse(this.response));
    })
  </script>

get 请求携带参数

get请求携带参数 :只有一种方式   在 url上来拼接!! 

post 请求携带参数

 携带的参数的位置 只能放在 send 方法中

参数类型 3种

 
'第1种' // 字符串的形式

// 请求的三大关键  1 请求地址  2 请求的方式  3 请求的参数???

      // post 请求 传递的参数
      // 1 只能放在 send中
      // 2 传递的参数的格式 3种格式
      //    2.1 字符串的形式  a=1&b=2&c=3   告诉后端(请求头 ) 我传递的数据是格式1
      //    2.2 json的格式     { a:1,b:2}   告诉后端(请求头 ) 我传递的数据是格式2
      //    2.3 FormData的格式               告诉后端(请求头 ) 我传递的数据是格式3

      const data = {
        bookname: '你不知道',
        author: '我自己你不知道',
        publisher: '斑马出版社',
        // 改为只有自己知道的key 长度 6-20
        appkey: 'xseresd',
      };
      // 将对象 转成 字符串
      const usp = new URLSearchParams(data);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://www.itcbc.com:3006/api/addbook');

      // 设置 请求头
      xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
      xhr.send(usp); // post请求的参数 只能放在 send
      xhr.addEventListener('load', function () {
        console.log(this.response);
      });
    </script>
'第2种' // json的格式

<script>
      // 请求的三大关键  1 请求地址  2 请求的方式  3 请求的参数???

      // post 请求 传递的参数
      // 1 只能放在 send中
      // 2 传递的参数的格式 3种格式
      //    2.1 字符串的形式  a=1&b=2&c=3   告诉后端(请求头 ) 我传递的数据是格式1
      //    2.2 json的格式     { a:1,b:2}   告诉后端(请求头 ) 我传递的数据是格式2
      //    2.3 FormData的格式               告诉后端(请求头 ) 我传递的数据是格式3

      const data = {
        bookname: '你不知道',
        author: '我自己你不知道',
        publisher: '斑马出版社',
        appkey: 'xseresd',
      };

      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://www.itcbc.com:3006/api/addbook');

      // 请求头
      xhr.setRequestHeader('content-type', 'application/json'); // 使用了 json格式

      // 把对象转成 json字符串的格式 再去传递 !  -axios 没有让我转格式 - 它内部做了封装处理 !!
      xhr.send(JSON.stringify(data));

      xhr.addEventListener('load', function () {
        console.log(this.response);
      });
    </script>
'第 3 种' FormData

 <input type="file" name="" id="" />
    <script>
      /* 
      FormData post 提交
      1 input标签 结合 file'类型 用户选择要上传的文件
      2 会触发input事件change 
      3 this.files获取到加载到浏览器内存文件 数组 
      4 new FormData 对象  调用 append 把文件添加进去
      5 使用ajax原生的代码。。。。。
      
       */

      // post 请求 传递的参数
      // 1 只能放在 send中
      // 2 传递的参数的格式 3种格式
      //    2.1 字符串的形式  a=1&b=2&c=3   告诉后端(请求头 ) 我传递的数据是格式1
      //    2.2 json的格式     { a:1,b:2}   告诉后端(请求头 ) 我传递的数据是格式2
      //    2.3 FormData的格式              告诉后端(请求头 ) 我传递的数据是格式3
                                           // 不需要自己单独指定,原生的代码内部会帮我们做

      const input = document.querySelector('input');
      input.addEventListener('change', function () {
      // 把表单的数据 存进来
        const file = this.files[0];
        
        // new 出一个 FormData 实例
        const fd = new FormData();
        
        // 把表单的值 添加进实例中
        fd.append('avatar', file);

        // new 出一个 XMLHttpRequest 实例
        const xhr = new XMLHttpRequest();
        
        // 调用open方法 (指定请求的类型、指定请求的url)
        xhr.open('POST', 'http://www.itcbc.com:3006/api/formdata');
        
        // FormData 不需要设置请求头
        // 开始发起请求
        xhr.send(fd);
        
        // 监听 数据响应
        xhr.addEventListener('load', function () {
          // 获取响应结果
          console.log(this.response);
        });
      });
    </script>