Interactive front-end and back-end of fetch

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43843173/article/details/102755206

Original author

1. Learn about the fetch

1, a modern version of the browser fetch comes, compatibility is not supported IE678 lower version of the browser, etc., if the data fetch request in the low version browser is inactive.
2 fetch promise + XMLHttpRequest is a combination of the way, it is accurate.
3. Note that not fetch ajax further package, he is js native.
4, fetch (url) returns a Promise object, so to define a storage container.
# The following is the relevant code explanation

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>现代版浏览器自带的fetch实现向后端请求数据</title>
</head>
<body>
    <p class="inp">
        <input type="button" value="点我发送请求" id="clickMe">
    </p>
    <p class="container">
        
    </p>
</body>
<script src="https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.js"></script>
</html>

Here is part js

        $("#clickMe").click(function(){
            //首先定义好一个请求数据的有效地址
            //在这里为了方便模拟,直接去JSONPlaceholder官网中随机找了个api接口,嘻嘻
            //JSONPlaceholder 是支持跨域请求的
            var url = 'http://jsonplaceholder.typicode.com/albums';

            //使用浏览器自带的fetch,其中fetch是原生的:ƒ fetch() { [native code] }
            // 但是fetch(url)会返回一个Promise对象,所以要定义一个容器来存储
            var responseData = fetch(url);

            //Promise是一个抽象的异步处理对象,当这个Promise生成后可以用then()
            // 方法来读取成功状态与失败返回状态的回调函数
            responseData.then((response)=>{
                //成功时返回的数据会存放在response.body流中,所以也需要一个定义容器来接收
                var responseData2 = response.json();

                console.log(responseData2);//返回的是一个Promise对象

                 //同时打印出来的还是一个Promise,还要进行一次处理
                responseData2.then((response)=>{
                    console.log(response);//响应的数据
                    //渲染数据
                    renderData(response);
                });

            },(error)=>{
                return error;
            });
        });

        function renderData(data){
            var _html = ``;
            data.forEach(ele => {
                _html += `
                    <div>
                        <p>id:${ele.id}</p>    
                        <p>Title:${ele.title}</p>    
                    </div>
                `
            });
            $(".container").html(_html);
        }
Well, here today came to an end. Happiness is probably the one you like sticking oh. . . . . .

Guess you like

Origin blog.csdn.net/qq_43843173/article/details/102755206