You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Ajax新手求助:如何从table_menu表获取数据并在users.php展示?

PHP实现Ajax获取菜单数据完整方案

别着急,我来帮你把这个PHP结合Ajax获取菜单数据的功能补全并解释清楚!咱们一步步来,让你能成功从table_menu表拿到数据并展示出来。


一、完善后端接口(users.php)

首先咱们把后端代码调整为返回JSON格式的数据(这是Ajax交互的最佳实践,比直接输出HTML更灵活),同时加入错误处理方便排查问题:

<?php
// users.php
// 引入数据库初始化文件
include 'config/initialize.php';

// 设置响应头为JSON格式,确保前端能正确解析
header('Content-Type: application/json');

// 初始化返回结果的结构
$result = [
    'success' => false,
    'data' => [],
    'message' => ''
];

// 先检查数据库连接是否正常
if (!$con) {
    $result['message'] = '数据库连接失败: ' . mysqli_connect_error();
    echo json_encode($result);
    exit;
}

// 执行菜单数据查询
$sql = "SELECT * FROM table_menu";
$res = mysqli_query($con, $sql);

if ($res) {
    // 遍历查询结果,把每条数据存入数组
    while ($row = mysqli_fetch_assoc($res)) {
        $result['data'][] = $row;
    }
    $result['success'] = true;
    $result['message'] = '成功获取' . count($result['data']) . '条菜单数据';
} else {
    $result['message'] = '查询失败: ' . mysqli_error($con);
}

// 释放结果集、关闭数据库连接
mysqli_free_result($res);
mysqli_close($con);

// 返回JSON格式的结果
echo json_encode($result);
?>

二、前端Ajax请求与数据展示

接下来写前端代码,这里提供两种方案:原生JavaScript(无需额外依赖)和jQuery(代码更简洁),你可以选自己顺手的。

方案1:原生JavaScript实现

把这段代码放在你要展示菜单的页面里(可以和users.php分开,也可以整合在同一个文件中):

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>餐厅菜单列表</title>
    <style>
        table { border-collapse: collapse; width: 80%; margin: 20px auto; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
        th { background-color: #f2f2f2; }
        img { border-radius: 4px; }
    </style>
</head>
<body>
    <h2 style="text-align: center;">餐厅菜单</h2>
    <!-- 用来存放生成的菜单表格 -->
    <div id="menu-container"></div>

    <script>
        // 页面加载完成后发起Ajax请求
        window.onload = function() {
            const xhr = new XMLHttpRequest();
            // 配置请求:GET方法,请求users.php接口,异步模式
            xhr.open('GET', 'users.php', true);
            // 设置响应类型为JSON
            xhr.responseType = 'json';
            
            // 请求成功时的处理逻辑
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const response = xhr.response;
                    if (response.success) {
                        // 构建表格HTML
                        let tableHtml = '<table><tr>' +
                                        '<th>菜单ID</th>' +
                                        '<th>菜品名称</th>' +
                                        '<th>价格</th>' +
                                        '<th>库存数量</th>' +
                                        '<th>菜品图片</th>' +
                                        '</tr>';
                        
                        // 遍历数据生成表格行
                        response.data.forEach(item => {
                            tableHtml += `<tr>
                                            <td>${item.menu_id}</td>
                                            <td>${item.menu_foodname}</td>
                                            <td>${item.menu_price}</td>
                                            <td>${item.menu_quantity}</td>
                                            <td><img src="${item.menu_image}" alt="${item.menu_foodname}" style="width: 80px; height: 60px; object-fit: cover;"></td>
                                        </tr>`;
                        });
                        
                        tableHtml += '</table>';
                        // 把表格插入到页面容器中
                        document.getElementById('menu-container').innerHTML = tableHtml;
                    } else {
                        // 查询失败时显示错误信息
                        document.getElementById('menu-container').innerHTML = `<p style="color: red; text-align: center;">${response.message}</p>`;
                    }
                } else {
                    document.getElementById('menu-container').innerHTML = `<p style="color: red; text-align: center;">请求失败,状态码:${xhr.status}</p>`;
                }
            };
            
            // 请求出错时的处理(比如网络问题)
            xhr.onerror = function() {
                document.getElementById('menu-container').innerHTML = '<p style="color: red; text-align: center;">网络请求出错,请检查网络连接</p>';
            };
            
            // 发送请求
            xhr.send();
        };
    </script>
</body>
</html>

方案2:jQuery实现(代码更简洁)

如果习惯用jQuery,先引入jQuery库,再写Ajax代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>餐厅菜单列表</title>
    <style>
        table { border-collapse: collapse; width: 80%; margin: 20px auto; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
        th { background-color: #f2f2f2; }
        img { border-radius: 4px; }
    </style>
    <!-- 引入jQuery库 -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
    <h2 style="text-align: center;">餐厅菜单</h2>
    <div id="menu-container"></div>

    <script>
        $(document).ready(function() {
            $.ajax({
                url: 'users.php',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        let tableHtml = '<table><tr>' +
                                        '<th>菜单ID</th>' +
                                        '<th>菜品名称</th>' +
                                        '<th>价格</th>' +
                                        '<th>库存数量</th>' +
                                        '<th>菜品图片</th>' +
                                        '</tr>';
                        // 遍历数据生成表格行
                        $.each(response.data, function(index, item) {
                            tableHtml += `<tr>
                                            <td>${item.menu_id}</td>
                                            <td>${item.menu_foodname}</td>
                                            <td>${item.menu_price}</td>
                                            <td>${item.menu_quantity}</td>
                                            <td><img src="${item.menu_image}" alt="${item.menu_foodname}" style="width: 80px; height: 60px; object-fit: cover;"></td>
                                        </tr>`;
                        });
                        tableHtml += '</table>';
                        $('#menu-container').html(tableHtml);
                    } else {
                        $('#menu-container').html(`<p style="color: red; text-align: center;">${response.message}</p>`);
                    }
                },
                error: function(xhr, status, error) {
                    $('#menu-container').html(`<p style="color: red; text-align: center;">请求出错:${error}</p>`);
                }
            });
        });
    </script>
</body>
</html>

三、几个注意事项

  1. 确保config/initialize.php里正确创建了数据库连接,并且$con变量是全局可用的;
  2. menu_image字段要存储图片的相对路径(比如uploads/tomato.jpg)或者完整URL,否则前端无法加载图片;
  3. 后续如果要做带参数的查询(比如按菜品名称搜索),一定要用MySQLi预处理语句来防止SQL注入风险。

内容的提问来源于stack exchange,提问作者Dan Canua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:51:19