JS详解-fetch核心语法

 document.querySelector('.btn').addEventListener('click',async () => {
            const p =  new URLSearchParams({pname:'浙江省',cname:'杭州市'})
            //1、如何请求?默认为get,参数1 url地址,返回promise
            const res = await fetch('http://hmajax.itheima.net/api/area?'+p.toString())

            if(res.status >= 200 && res.status < 300)
            {
            //2、如何处理响应(JSON),.json方法解析json返回promise
            const data = await res.json()
            }
            else{
            //3、处理异常
            console.log('请求异常',res.status)
            }
        })

fetch提交FormData:

        document.querySelector('.ipt').addEventListener('change',async function(){
           // querySelector获取的是一个dom对象,files是一个文件列表,[0]是第一个文件
            const img = this.files[0]
            // 创建一个formdata对象
            const data = new FormData()
            data.append('img',img)
            const res = await fetch('http://hmajax.itheima.net/api/uploadimg', {
                // 请求方法
                method: 'POST',
                // 提交数据
                body: data
            })
            // 解析返回的json数据
            const resData = await res.json()
            // 回显
            document.querySelector('.icon').src = resData.data.url

fetch提交JSON:

document.querySelector('.btn').addEventListener('click',async function(){
           // 实例化Headers对象
              const headers = new Headers()
            // append 添加keyvalue
                headers.append('Content-Type','application/json')

                const res = await fetch('https://jsonplaceholder.typicode.com/posts',{
                    method: 'POST',
                    headers,
                    // JSON.stringify()将对象转换为json字符串
                    body: JSON.stringify({
                        title: 'foo',
                        body: 'bar',
                        userId: 1
                    })
                })
                // res.status 判断状态码
                const data = await res.json()
                console.log(data)
        })

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值