jQuery实现从后端获取数据并渲染到页面

话不多说,先上效果

点击按钮,实现页面渲染

接口文档

注:接口文档和后端地址来源于【黑马程序员微信小程序开发前端教程_零基础玩转微信小程序】 https://www.bilibili.com/video/BV1nE41117BQ/?p=57&share_source=copy_web&vd_source=81202236c582d64e6a1e57dd79b18f0f B站视频课程

实现代码

<!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>

总结:

  1. 用jQuery向https://api-hmugo-web.itheima.net/api/public/v1/home/catitems发送get请求来获取数据

  1. 获取数据成功后通过 $("body").append( )将数据渲染到页面上(这里还用到了模板字符串)

猜你喜欢

转载自blog.csdn.net/weixin_53141315/article/details/129459056