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

如何从HTML页面跳转至.php页面并加载对应品类的动态商品内容

实现方案

第一步:修改首页导航链接,传递品类参数

在index.html的导航区域,给每个品类的跳转链接加上GET参数category,参数值和你JSON文件中存储的品类标识保持一致即可:

<!-- index.html 导航示例代码 -->
<nav>
  <a href="aisle.php?category=fruit">水果</a>
  <a href="aisle.php?category=meat">肉类</a>
  <a href="aisle.php?category=snack">零食</a>
  <!-- 其余品类按相同格式补充即可 -->
</nav>

第二步:在aisle.php中接收参数并校验

通过PHP的$_GET全局变量接收传递过来的品类参数,同时添加基础校验避免非法访问。

第三步:读取JSON文件并筛选对应品类商品

读取你的商品JSON文件,解析为PHP数组后,筛选出品类匹配的所有商品。

第四步:渲染商品到页面

把筛选后的商品循环输出到页面结构中。


完整代码示例

aisle.php 完整代码

<?php
// 配置允许的品类列表,值需要和JSON文件中的category字段、首页链接的参数值完全对应
$allowed_categories = ['fruit', 'meat', 'snack'];
$category_map = [
    'fruit' => '水果专区',
    'meat' => '肉类专区',
    'snack' => '零食专区'
];

// 接收并校验品类参数
$current_category = isset($_GET['category']) ? trim($_GET['category']) : '';
if (!in_array($current_category, $allowed_categories)) {
    die("请求的品类不存在,请返回首页重新选择");
}

// 读取并解析JSON商品数据
$json_file = 'products.json'; // 替换为你的JSON文件实际路径
if (!file_exists($json_file)) {
    die("商品数据加载失败,请稍后重试");
}
$product_json = file_get_contents($json_file);
$all_products = json_decode($product_json, true);

// 筛选当前品类的商品
$target_products = [];
foreach ($all_products as $product) {
    if ($product['category'] === $current_category) {
        $target_products[] = $product;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title><?php echo $category_map[$current_category]; ?></title>
</head>
<body>
    <h1><?php echo $category_map[$current_category]; ?></h1>
    <div class="product-list">
        <?php if (empty($target_products)): ?>
            <p>当前品类暂无上架商品</p>
        <?php else: ?>
            <?php foreach ($target_products as $item): ?>
            <div class="product-card">
                <h3><?php echo $item['name']; ?></h3>
                <p>售价:¥<?php echo $item['price']; ?></p>
                <p><?php echo $item['description']; ?></p>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <a href="index.html">返回首页</a>
</body>
</html>

products.json 结构参考

你的JSON文件需要和以下结构对应,可根据自己的需求增减字段:

[
    {
        "name": "红富士苹果",
        "category": "fruit",
        "price": 8.99,
        "description": "新鲜应季,脆甜多汁"
    },
    {
        "name": "冷鲜猪后腿肉",
        "category": "meat",
        "price": 32.99,
        "description": "散养土猪,当天现杀"
    },
    {
        "name": "原味薯片",
        "category": "snack",
        "price": 6.99,
        "description": "非油炸,无添加"
    }
]

注意事项

  • 首页链接的category参数值、$allowed_categories数组的值、JSON文件中category字段的值三者必须完全一致,区分大小写,否则会筛选不到商品
  • 如果需要新增品类,只需要在三个位置同步添加对应标识即可
  • 校验逻辑不要省略,可避免参数非法、文件丢失等情况导致的页面报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:57:03