jQuery implements getting data from the backend and rendering it to the page

Not much to say, let's start with the effect

Click the button to achieve page rendering

interface documentation

Note: The interface document and back-end address are from [Dark Horse Programmer WeChat Mini Program Development Front-end Tutorial_Zero-Basic Fun with WeChat Mini Program] https://www.bilibili.com/video/BV1nE41117BQ/?p=57&share_source=copy_web&vd_source= 81202236c582d64e6a1e57dd79b18f0f B station video course

implement the code

<!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>
    <script src="../js/jquery.js"></script>
    <style>
        button{
            width: 200px;
            height: 100px;
            background-color: #59de8c;
        }
        .box{
            float: left;
            margin-left: 50px;
            padding-top: 30px;
            width: 200px;
            height: 250px;
            background-color: #df75c1;
            text-align: center;
            color: aquamarine;
            text-shadow: 2px 2px 2px red;
        }
    </style>
</head>
<body>
    <button>点击后用jQuery渲染页面</button>
        <script>
            $('button').click(function(){
                // 按钮点击后隐藏
                $(this).hide()
                // 发送get请求
                $.ajax({
                type:'get',
                url:'https://api-hmugo-web.itheima.net/api/public/v1/home/catitems',
                success:function(data){  
                    //将获取到的数据渲染到页面上
                   for(let i = 0; i < data.message.length;i++){
                    $("body").append(`<div class="box">
                            <img src=${data.message[i].image_src} alt="">
                            <h2>标题:${data.message[i].name}</h2>
                     </div>`)
                   }
                }
            })
            })
        </script>
</body>
</html>

Summarize:

  1. Use jQuery to send a get request to https://api-hmugo-web.itheima.net/api/public/v1/home/catitems to get the data

  1. After the data is successfully obtained, the data is rendered to the page through $("body").append( ) (the template string is also used here)

Guess you like

Origin blog.csdn.net/weixin_53141315/article/details/129459056