前端发送Ajax请求数据的几种常见方法(三) fetch方法发送

传统的xhr请求写起来非常的混乱,但是使用fetch之后,如下所示:这种链式调用的风格看上去会非常舒服。

1.fetch发送get请求:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // get
    fetch(
        "https://api.apiopen.top/getSingleJoke?sid=28654780"
    ).then((res) => {
            // res拿到的是响应报文,需要解析
            return res.json();
            // 返回数据是json字符串,就可以解析成json格式
            // res.json返回的是一个promise对象
            // 就可以解析成字符串格式
            // res.text返回的是一个promise对象
        }).then((data) => {
            // data就是解析成功的格式数据
            console.log(data);
        });
</script>

</html>

2.fetch发送post请求:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

</head>

<body>

</body>
<script>
    fetch("https://api.apiopen.top/getSingleJoke", {
        method: "POST",
        headers: { // 设置请求头
            "content-type": "application/x-www-form-urlencoded",
        },
        body: `sid = 28654780`,
    }).then((res) => {
            // 解析:
            return res.json();
        }).then((data) => {
            console.log(data);
        });
</script>

</html>

当然,fetch方法还能搭配vue一起使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值