03-Ajax第三天学习笔记

1. xhr的基本使用
  1. 使用xhr发起get请求
        // 声明一个xhr对象
        let xhr = new XMLHttpRequest()
        // 调用open函数,创建请求
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
        // // 带参数的请求
        // xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
        // 调用send函数,发送请求
        xhr.send()
        // 监听onreadystatechange事件
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText)
            }
        }
  1. xhr的readyState属性,用来表示当前Ajax请求所处的状态。4表示Ajax请求完成
  2. 查询字符串:指在url的末尾加上用于向服务器发送信息的字符串(变量)。多个参数使用&分隔
  3. 使用xhr发起post请求
        // 创建对象
        const xhr = new XMLHttpRequest()
        // 使用open函数
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
        // 设置Content-Type属性
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        // send函数
        xhr.send('bookname=剑来&author=烽火戏诸侯&publisher=lz')
        // 监听事件
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText)
            }
        }
2. url编码
  1. 概念:url地址不允许出现非英文字符,所以需要将其他字符编码为英文字符
  2. 编码与解码方法:浏览器提供了url编码与解码的api。encodeURL()编码函数,decodeURL解码函数
3. 数据交换格式
  1. xml
  2. json:全称:JavaScript Object Notation,即JavaScript对象表示法。
    1. json就是JavaScript对象和数组的字符串表示法,本质是字符串
    2. 作用:json是一种轻量级的文本数据交换格式,用于传输数据,比xml更小,更快,更易解析。
    3. json语法注意事项:(1)属性名和字符串必须使用双引号包裹(2)json中不能写注释(3)json最外层必须是对象或数组格式(4)不能使用undefined和函数作为json的值
    4. json与js对象的转换:JSON.parse()==json转js对象(反序列化),JSON.stringify()==js转json(序列化)
4. 封装Ajax函数
    // 将data数据转化为查询字符串
    function selectData(data) {
        const arr = []
        for(let k in data) {
            arr.push(k + '=' + data[k])
        }
        str = arr.join('&')
        return str
    }

    // 封装xhr请求函数
    function lz(obj) {
        const xhr = new XMLHttpRequest()
        // 将data数据转化为查询字符串
        let qs = selectData(obj.data)
        // 判断method类型
        if(obj.method === 'GET') {
            xhr.open('GET',obj.url + '?' + qs)
            xhr.send()
        }else if(obj.method === 'POST'){
            xhr.open('POST',obj.url)
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(qs)
        }
        // 监听事件
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                let result = JSON.parse(xhr.responseText)
                obj.success(result)
            }
        }
    }
5. xhr level2新特性
  1. 可以设置http请求时限
        // 设置时限
        xhr.timeout = 30
        xhr.ontimeout = function() {
            console.log('请求超时')
        }
  1. FormData对象管理表单数据
        // 创建formdata对象
        const fd = new FormData()
        // 添加数据
        fd.append('bookname','剑来')
        fd.append('author','烽火戏诸侯')
        fd.append('publisher','lz')
        // 创建对象
        const xhr = new XMLHttpRequest()
        // 使用open函数
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
        // 设置Content-Type属性
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        // send函数
        xhr.send(fd)
        // 监听事件
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                console.log(JSON.parse(xhr.responseText))
            }
        }
  1. 上传文件
    <!-- 1. 文件选择框 -->
  <input type="file" id="file1" />
  <!-- 2. 上传文件的按钮 -->
  <button id="btnUpload">上传文件</button>
  <br />
  <!-- 3. img 标签,来显示上传成功以后的图片 -->
  <img src="" alt="" id="img" width="800" />

  <script>
    const btnUpload = document.querySelector('#btnUpload')
    btnUpload.addEventListener('click', function() {
        const files = document.querySelector('#file1').files
        if(files.length <= 0) {
            return alert('请选择要上传的文件')
        }
        // 将文件放入formdata中
        const fd = new FormData()
        fd.append('avatar',files[0])
        // 发起请求
        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
        xhr.send(fd)

        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                const str = JSON.parse(xhr.responseText)
                // console.log(str)
                if(str.status === 200) {
                    document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + str.url
                }else{
                    console.log('上传失败')
                }
            }
        }
    })
  </script>
  1. 显示文件上传进度
        // 显示上传进度
        xhr.upload.onprogress = function(e) {
          if(e.lengthComputable) {
            let count = Math.ceil((e.loaded / e.total) * 100)
            console.log(count)
          }
        }
6. axios
  1. 概念:axios是专注于网络数据请求的js库,相比于原生xhr更简单易用,相比于jQuery更轻量化。
  2. axios发起请求
    <button id="btn1">发起GET请求</button>
    <button id="btn2">发起POST请求</button>
    <button id="btn3">直接使用axios发起GET请求</button>
    <button id="btn4">直接使用axios发起POST请求</button>
    <script>
        // 发起GET请求
        document.querySelector('#btn1').addEventListener('click', function() {
            const url = 'http://www.liulongbin.top:3006/api/get'
            const paramsObj = {name:'lz',age:20}
            axios.get(url,{params : paramsObj}).then(function(res) {
                const result = res.data
                console.log(result)
                console.log(res)
            })
        })
        // 发起POST请求
        document.querySelector('#btn2').addEventListener('click', function() {
            const url = 'http://www.liulongbin.top:3006/api/post'
            const dataObj = {location:'lz',address:20}
            axios.post(url,dataObj).then(function(res) {
                const result = res.data
                console.log(result)
                console.log(res)
            })
        })
        // 直接使用axios发起请求
        axios({
            method: 'GET/POST',
            url: '',
            data: {post参数},
            params:get参数,
        }).then(function() {})
    </script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值