数据库结构及内容如下:

PHP处理

<?php
// 链接数据库

require_once('conn.php');
// 头部声明为json
header("Content-type:application/json");
try {
  // 数据库语句
  $sql = "select * from nav";
  // 有返回结果集,使用query函数,该函数返回结果为预处理对象。
  $stmt = $conn->prepare($sql);
  $stmt->execute();
  $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
  // 转json输出
  echo json_encode($res, JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
  echo $e->getMessage();
}

输出的结果

[
  {
    "id": "1",
    "navname": "岳泽以",
    "navlink": "https://www.yuezeyi.com/",
    "icon": "https://pic.zeyiwl.cn/yunimg/202304171028533.jpg",
    "xuhao": "3"
  },
  {
    "id": "2",
    "navname": "百度",
    "navlink": "https://www.baidu.com/",
    "icon": "https://pic.zeyiwl.cn/yunimg/202304171028533.jpg",
    "xuhao": "2"
  },
  {
    "id": "3",
    "navname": "腾讯",
    "navlink": "https://www.baidu.com/",
    "icon": "https://pic.zeyiwl.cn/yunimg/202304171028533.jpg",
    "xuhao": "1"
  }
]

HTML内容:

<!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>
  <style>
    body {
      background: #f5f5f5;
    }

    .item {
      display: flex;
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      background: #fff;
      border-bottom: 1px solid #e5e5e5;
      margin-bottom: 10px;
      justify-content: space-between;
    }

    .item .item-title {
      height: 50px;
    }

    .item .item-title img {
      width: 50px;
    }

    .item .item-content {
      color: #9D9D9D;
      margin-right: 20px;
      font-size: 16px;
      line-height: 50px;
    }
  </style>
</head>

<body>
  <!--页面容器-->
  <div id="container">
    <!--每个条目-->
    <div class="item">
      <div class="item-title">
        <img src="https://pic.zeyiwl.cn/yunimg/202304151026022.png" alt="">
      </div>
      <div class="item-title">
        <span class="item-content">岳泽以博客</span>
      </div>
    </div>
  </div>
</body>
<!-- ajax请求并渲染数据 -->
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
  $.ajax({
    //请求方式
    type: 'get',
    //发送请求的地址
    //我这里的地址是不需要传数据的,所以没有拼接参数
    url: 'cha.php',
    //服务器返回的数据类型
    dataType: 'json',
    //请求成功的处理
    success: function (data) {
      console.log(data);
      //拼接字符串
      var str = '';
      //对数据做遍历,拼接到页面显示
      for (var i = 0; i < data.length; i++) {
        str += '<div class="item">' +
          '<div class="item-title"><img src="' + data[i].icon + '" alt=""></div>' +
          '<div class="item-title">' +
          '<span class="item-content">' + data[i].navname + '</span>' +
          '</div>' +
          '</div>';
      }
      //放入页面的容器显示
      $('#container').html(str);

    },
    //请求失败的处理
    error: function (jqXHR) {
      console.log(jqXHR);
    }
  });

</script>

</html>

End
最后修改:2023 年 04 月 17 日
如果觉得我的文章不错,请随手点赞~