2022/8/12 xhr的基本使用以及替换的内容和跨域同源原理以及上传文件的案例

 利用xhr请求get参数(感觉没用,jq的$.ajax就可以解决了)

 //创建xhr对象
        let xhr = new XMLHttpRequest()
        //调用open函数,?后的字符串叫做:查询字符串
        xhr.open('GET','http://liulongbin.top:3006/api/getbooks?id=1&bookname=西游记')
        //调用send函数
        xhr.send()
        //监听事件
        xhr.onreadystatechange = function () {
            if(xhr.readyState===4&&xhr.status===200){
                //获取服务器响应的数据
                console.log(xhr.responseText)
            }
        }

JOSN  和 JS 转换

  let josnstr = '{"a":"hello","b":"world"}'
         console.log(JSON.parse(josnstr))
        let str = {
            a : 'wo',
            b : 'ow'
        }
        console.log(JSON.stringify(str))

自己写ajax,感觉完全没意义,参照教程写的

function res (data) {
    let arr = []
    for (let k in data) {
        let str = k+'='+data[k]
        arr.push(str)
    }
    return arr.join('&')
}
function itheima (options) {
    let xhr = new XMLHttpRequest()
    //把外界传递过来的参数对象转为查询字符串
    let qs = resolveData(options,data)
    if(options.method.toUpperCase()==='GET'){
        //发送get请求
        xhr.open(options.method,options.url+'?'+qs)
        xhr.send()

    }else if(options.method.toUpperCase()==='post'){
        //发送post请求
        xhr.open(options.method,options.url)
        xhr.setRequestHeader('Content-Type','application/x-www/form-urlencoded')
        xhr.send(qs)

    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState===4&& xhr.status===200) {
           let ress = JSON.parse(xhr.responseText)
           options.succsee(ress)
        }
    }
}
 let xhr = new XMLHttpRequest()
        //设置时间
        xhr.timeout = 3000
        //指定超时的回调函数
        //xhr.addEventListener('timeout',()=>console.log('请求超时'))
        xhr.ontimeout = function () {
            console.log('请求超时')
        }
        xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
        xhr.send()
        xhr.onreadystatechange = function () {
            if(xhr.readyState === 4 && xhr.status===200){
                console.log(xhr.response
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值