如何在PHP中生成指定结构的JSON?含API修改与HTML访问方案
如何修正REST API的JSON结构并在HTML中访问数据
首先得明确:你想要的原始JSON结构存在语法错误——同一个对象里不能有重复的键,所以咱们得把banner和hotdeals都改成数组,这样才符合JSON规范。最终合理的结构可以选两种:
方案1:纯路径数组(简洁版)
{ "banner": [ "/Home/Banner/activity.png", "/Home/Banner/fitness.png" ], "hotdeals": [ "/Home/HotDeals/hotdeal1.png", "/Home/HotDeals/hotdeal2.png", "/Home/HotDeals/hotdeal3.png" ] }
方案2:带键名的对象数组(保留原字段名)
{ "banner": [ {"homuri": "/Home/Banner/activity.png"}, {"homuri": "/Home/Banner/fitness.png"} ], "hotdeals": [ {"hotdeal": "/Home/HotDeals/hotdeal1.png"}, {"hotdeal": "/Home/HotDeals/hotdeal2.png"}, {"hotdeal": "/Home/HotDeals/hotdeal3.png"} ] }
下面咱们一步步解决问题:
修正PHP代码生成合规JSON
核心思路是把banner和hotdeals的数据分别归类到两个数组里,最后组合成一个结构化的关联数组,而不是把所有条目混在一起。
<?php include('dbconn.php'); $request = $_SERVER['REQUEST_METHOD']; switch($request) { case 'GET': response(getData()); break; } function getData() { global $conn; @$col = $_GET['col']; // 初始化结构化结果数组 $result = [ 'banner' => [], 'hotdeals' => [] ]; // 获取首页横幅数据 $query = mysqli_query($conn, "select strHomeBannerUri as homuri from tblhomebannerdetails"); while($row = mysqli_fetch_assoc($query)) { // 选方案1就用:$result['banner'][] = $row['homuri']; // 选方案2就用下面这句(保留原字段名) $result['banner'][] = $row; } // 如果参数col为pop,获取热门商品数据 if($col == "pop") { $query = mysqli_query($conn, "select nHotrDealImageUri as hotdeal from tblhotdealimages"); while($row = mysqli_fetch_assoc($query)) { // 选方案1就用:$result['hotdeals'][] = $row['hotdeal']; // 选方案2就用下面这句 $result['hotdeals'][] = $row; } } return $result; } function response($data) { // 设置正确的响应头,确保客户端识别为JSON header('Content-Type: application/json'); echo json_encode($data); } ?>
我特意加了header('Content-Type: application/json'),避免客户端解析数据时出现异常,你可以根据需求选择方案1或方案2的代码。
在HTML中访问并渲染数据
咱们用JavaScript的fetch API来获取数据,然后动态把图片渲染到页面上,示例代码如下:
<!DOCTYPE html> <html> <head> <title>加载API数据</title> <style> img { max-width: 300px; margin: 10px; } </style> </head> <body> <h2>首页横幅</h2> <div id="banner-container"></div> <h2>热门商品</h2> <div id="hotdeals-container"></div> <script> // 调用API,假设你的PHP文件名为api.php,传col=pop获取热门商品 fetch('api.php?col=pop') .then(response => { if (!response.ok) throw new Error('请求失败'); return response.json(); }) .then(data => { // 渲染首页横幅(对应方案2的结构,若用方案1则改为item而非item.homuri) const bannerContainer = document.getElementById('banner-container'); data.banner.forEach(item => { const img = document.createElement('img'); img.src = item.homuri; img.alt = '首页横幅'; bannerContainer.appendChild(img); }); // 渲染热门商品(对应方案2的结构,若用方案1则改为item而非item.hotdeal) const hotdealsContainer = document.getElementById('hotdeals-container'); data.hotdeals.forEach(item => { const img = document.createElement('img'); img.src = item.hotdeal; img.alt = '热门商品'; hotdealsContainer.appendChild(img); }); }) .catch(error => { console.error('加载数据出错:', error); }); </script> </body> </html>
如果需要兼容旧浏览器,可以把fetch换成XMLHttpRequest,核心逻辑是一致的:发送请求→解析JSON→渲染DOM。
内容的提问来源于stack exchange,提问作者Manisha
相关产品推荐
相关产品推荐

