Fetch 用法

Fetch 用法

promise

promise是es6中的对象

promise <->成功/失败 异步

new Promise((resolve,reject)=>{
    //resolve 成功   reject  失败
    resolve(num)//将会走成功的then回调
    reject(num)//将会走失败的then回调
}).then((num)=>{
    alert('成功',num)
},(num)=>{
    alert('失败',num)
})

Fetch

<input type="text" name="" id="username"><br>
<input type="password" name="" id="psw">
<button class="login">
    登录
</button>

get

document.querySelector('.login')['onclick']=x=>{
    fetch(`http//localhost:8080/login?user=${user.value}&psw=${psw.value}`,{
        method:'GET'
    }).then((res)=>{
        res.json(()=>{//这是一个promise实例
            
        }).then(()=>{//成功
            
        }).catch(()=>{//失败
            console.log('服务器错误')
        })
    })
}

post

document.querySelector('.login')['onclick']=x=>{
    fetch(`http//localhost:8080/login`,{
        method:'POST',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'//需要声明  传字符串
        }
        body:`user=${user.value}&psw=${psw.value}`//非明文
    }).then((res)=>{
        res.json(()=>{
            
        }).then(()=>{//成功
            //做事
        }).catch(()=>{//失败
            console.log('服务器错误')
        })
    })
}

传图片

头像<input type="file" id="fl">
document.querySelector('.login')['onclick']=x=>{
    //console.log(fl.files[0])
    let fd = new FormData()
    fd.append('pic',fl.files[0])
    fetch('http//localhost:8080/login',{
        method:'POST',
        body:fd,
    }).then((res)=>{
        
    }).then((res)=>{
        var {ok} = res
        if(ok){
            let {dataUrl} = res;
            console.log(dataUrl)
        }
    }).catch(()=>{
        console.log("服务器错误")
    })
        
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值