fetch请求

117 阅读1分钟
<!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>
        <script>
            // fetch() 是es6新增的语法,用于替代繁琐的原生ajax请求,实质是对原生ajax的封装
            // fetch不设置请求方式,默认是get请求,不建议用fetch发送post请求
            fetch("https://autumnfish.cn/search?keywords=薛之谦").then(
                (res) => {
                    // fetch请求下的数据并不是响应结果,而是一个信息对象,需要使用json()函数把信息对象解析成响应的json数据
                    // console.log(res.json());
                    // res.json()解析的结果是一个promise对象,需要调用then拿结果
                    res.json().then((res) => {
                        console.log(res);
                    });
                }
            );

            fetch("https://autumnfish.cn/search?keywords=薛之谦")
                .then((res) => res.json())
                .then((res) => {
                    console.log(res);
                });

            // 箭头函数省略写法:当箭头函数的函数体中只有一句return时,return和{}可以省略
            // (x) => {
            //     return x + 1;
            // };
            // 可以省略为
            // (x) => x + 1;
        </script>
    </body>
</html>