How can I retrieve data from the database using layui?

Layui is a frontend UI framework that does not have built-in functionality to fetch data from a database. Typically, fetching database data is achieved through backend programming languages and database operations.

You can use a backend programming language (such as PHP, Java, Python, etc.) to connect to the database, write the corresponding code to retrieve data, and then return the data to the frontend through an interface.

Here is an example using PHP and MySQL database:

<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);

// 查询数据库
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// 获取数据
$data = [];
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// 返回数据
echo json_encode($data);

// 关闭数据库连接
$conn->close();
?>

In the front end, you can use Layui’s Ajax request to call this interface and retrieve data, then display it on the page.

layui.use('jquery', function(){
  var $ = layui.jquery;
  
  $.ajax({
    url: 'your_backend_api_url',
    method: 'GET',
    success: function(data){
      // 在这里处理获取到的数据
      console.log(data);
    },
    error: function(){
      // 错误处理
    }
  });
});

Please note that the above code is just a simple example, the specific implementation will vary based on the backend language and database you are using.

bannerAds