修复本地服务器上读取data.json的航班搜索页面故障求助
问题排查与修复方案
你的代码存在PHP读取JSON错误、键名不匹配、浏览器端JS无法使用require、DOM元素缺失这几个核心问题,以下是具体修复步骤和完整代码:
错误点拆解
1. PHP 部分问题
- 不能用
require()加载JSON文件,该函数仅用于加载PHP脚本,需用file_get_contents()读取文件内容,再用json_decode()解析为数组 - JSON数据外层包含
data键,遍历需指向$data['data']而非直接遍历$data - 键名完全不匹配:JSON中的键是
City/Airport、Country、IATA code,但PHP代码里误用了city、country、iataCode
2. JavaScript 部分问题
- 浏览器环境不支持Node.js的
require()语法,需用fetch API异步获取JSON数据 - 包含特殊字符(空格、斜杠)的键名,不能用
.访问,必须用方括号语法obj['Key Name'] - 代码中引用了
fromLabel和toLabel元素,但HTML里未定义,会导致运行时报错
修复后的完整代码
data.json(保持不变)
{ "data": [ { "City/Airport": "Aarhus", "Country": "Denmark", "IATA code": "AAR" }, { "City/Airport": "Abadan", "Country": "Iran", "IATA code": "ABD" }, { "City/Airport": "Abeche", "Country": "Chad", "IATA code": "AEH" } ] }
修复后的HTML/PHP代码
<!DOCTYPE html> <html> <head> <title>Flight Search</title> </head> <body> <h1>Flight Search</h1> <!-- 添加缺失的标签元素 --> <div> <label for="from">From: </label> <span id="fromLabel"></span> </div> <div> <label for="to">To: </label> <span id="toLabel"></span> </div> <form> <select name="from" id="from"> <option value="">Select a city</option> <?php // 正确读取并解析JSON $jsonContent = file_get_contents('./data.json'); $data = json_decode($jsonContent, true); // 遍历data数组 foreach ($data['data'] as $city) { // 使用正确的键名 echo '<option value="' . $city['IATA code'] . '">' . $city['City/Airport'] . ', ' . $city['Country'] . '</option>'; } ?> </select> <select name="to" id="to"> <option value="">Select a city</option> <?php $jsonContent = file_get_contents('./data.json'); $data = json_decode($jsonContent, true); foreach ($data['data'] as $city) { echo '<option value="' . $city['IATA code'] . '">' . $city['City/Airport'] . ', ' . $city['Country'] . '</option>'; } ?> </select> <input type="submit" value="Search"> </form> <script> // 用fetch替代require获取JSON fetch('./data.json') .then(response => response.json()) .then(jsonData => { const cities = []; // 遍历data数组,用方括号访问特殊键名 for (const city of jsonData.data) { cities.push({ name: city['City/Airport'], country: city['Country'], iataCode: city['IATA code'] }); } const from = document.getElementById('from'); const to = document.getElementById('to'); const fromLabel = document.getElementById('fromLabel'); const toLabel = document.getElementById('toLabel'); from.addEventListener('change', () => { const iataCode = from.options[from.selectedIndex].value; const city = cities.find(city => city.iataCode === iataCode); // 处理未选择的情况,避免报错 fromLabel.textContent = city ? city.name : ''; }); to.addEventListener('change', () => { const iataCode = to.options[to.selectedIndex].value; const city = cities.find(city => city.iataCode === iataCode); toLabel.textContent = city ? city.name : ''; }); }) .catch(error => console.error('Failed to load data:', error)); </script> </body> </html>
额外优化建议
- 可以把PHP读取JSON的逻辑封装成函数,避免重复代码
- 添加加载状态提示,提升用户体验
- 对提交操作做基本校验,避免空值提交
内容的提问来源于stack exchange,提问作者Sakhr Net
相关产品推荐
相关产品推荐

