fetch使用详解

参数说明

fetch参数:一个必选的资源路径和一个可选的参数init。无论请求是否成功都返回一个Promise

与$.ajax()的不同

fetch与$.ajax()的不同

  1. 当接收到类似404或500这类表示错误的状态码时,fetch返回的Promise对象的状态仍然为resolve(resolve的返回值‘ok’属性设置为false),仅当网络故障时或请求被阻止时,才会标记为 reject
  2. 默认情况下fetch 不会从服务端发送或接收任何 cookies, 如果站点依赖于用户 session,则会导致未经认证的请求(要发送 cookies,必须设置 credentials 选项)

示例

不带参数的请求

fetch('http://www.tingchunyu.com/test/fetch_test/fetch_test.php').then(response=>{
    // response为HTTP响应
    return response.json()// 将HTTP响应转为json数据
}).then(data=>{
    console.log(data)// 打印json数据
}).catch(error=>{// 捕获异常
    console.log(error)
})

在这里插入图片描述
上面代码获取了一个json字符串,其中response为HTTP响应。如果要得到json数据需要使用.json()方法进行转换。

带参数的请求(以post为例)

fetch('http://www.tingchunyu.com/test/fetch_test/fetch_getuser_test.php', {
    body: JSON.stringify({id:666}),//这里是要传递的参数
    headers: {
        'content-type': 'application/json'
    },
    method: 'POST',
})
    .then(response => response.json())
    .then(data=>{
        console.log(data)
    })

在这里插入图片描述
注意:如果后台接收不到数据请参考这篇文章

判断请求是否成功

因为 这个 的原因,resolved状态不一定代表请求成功,所以需要在resolved的状态下再次判断Response.ok,如下代码:

fetch('http://www.tingchunyu.com/test/fetch_test/fetch_test.php')
    .then(response => {
        if (response.ok) {
            return response.json()
        }
        throw new Error('请求失败')
    })
    .then(data => {
        console.log(data)
    })
    .catch(error => {
        console.log(error)
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值