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

使用Javascript结合HTML/PHP实现双值匹配的CSV特定行查询

解决方案:从CSV文件查询区域间距离

我来帮你实现这个需求,下面是完整的实现方案,包含PHP读取CSV数据、前端表单构建以及交互逻辑:

1. 准备工作

首先确保你的CSV文件(命名为zones.csv)和代码文件放在同一目录下,文件格式和你提供的示例一致(分隔符为分号;)。

2. 完整代码实现

这个方案结合了PHP处理CSV数据和前端JavaScript交互,你可以直接复制使用:

<?php
// 读取CSV文件并处理数据
$csvFile = 'zones.csv';
// 跳过空行,读取所有数据
$csvData = array_map('str_getcsv', file($csvFile, FILE_SKIP_EMPTY_LINES));
// 移除表头行
$header = array_shift($csvData);

// 提取所有唯一的区域(编码+名称),用于生成下拉选项
$zones = [];
foreach ($csvData as $row) {
    $fromCode = $row[0];
    $fromName = $row[1];
    if (!isset($zones[$fromCode])) {
        $zones[$fromCode] = $fromName;
    }
    $toCode = $row[2];
    $toName = $row[3];
    if (!isset($zones[$toCode])) {
        $zones[$toCode] = $toName;
    }
}

// 构建距离查询映射表:[出发编码][到达编码] => 距离值
$distanceMap = [];
foreach ($csvData as $row) {
    $fromCode = $row[0];
    $toCode = $row[2];
    $distanceMap[$fromCode][$toCode] = $row[4];
}

// 处理AJAX请求(如果用后端查询方式)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['from']) && isset($_POST['to'])) {
    $fromCode = $_POST['from'];
    $toCode = $_POST['to'];
    $distance = isset($distanceMap[$fromCode][$toCode]) ? $distanceMap[$fromCode][$toCode] : null;
    echo json_encode(['distance' => $distance]);
    exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>区域距离查询</title>
</head>
<body>
    <h3>区域间距离查询</h3>
    <div>
        <label for="fromZone">出发区域:</label>
        <select id="fromZone">
            <?php foreach ($zones as $code => $name): ?>
                <option value="<?php echo htmlspecialchars($code); ?>">
                    <?php echo htmlspecialchars($name); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div style="margin-top: 10px;">
        <label for="toZone">到达区域:</label>
        <select id="toZone">
            <?php foreach ($zones as $code => $name): ?>
                <option value="<?php echo htmlspecialchars($code); ?>">
                    <?php echo htmlspecialchars($name); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <button id="getDistanceBtn" style="margin-top: 15px;">获取距离</button>
    <div id="resultArea" style="margin-top: 20px; font-weight: bold;"></div>

    <script>
    // 方式1:纯前端查询(数据量小时推荐)
    // 把PHP生成的距离映射转换为JS对象
    const distanceMap = <?php echo json_encode($distanceMap); ?>;

    document.getElementById('getDistanceBtn').addEventListener('click', function() {
        const fromCode = document.getElementById('fromZone').value;
        const toCode = document.getElementById('toZone').value;
        
        if (distanceMap[fromCode] && distanceMap[fromCode][toCode]) {
            document.getElementById('resultArea').textContent = `距离:${distanceMap[fromCode][toCode]}`;
        } else {
            document.getElementById('resultArea').textContent = '错误:未找到该路线的距离数据';
        }
    });

    // // 方式2:AJAX后端查询(数据量大时推荐,取消注释即可使用)
    // document.getElementById('getDistanceBtn').addEventListener('click', function() {
    //     const fromCode = document.getElementById('fromZone').value;
    //     const toCode = document.getElementById('toZone').value;
        
    //     fetch(window.location.href, {
    //         method: 'POST',
    //         headers: {
    //             'Content-Type': 'application/x-www-form-urlencoded',
    //         },
    //         body: `from=${fromCode}&to=${toCode}`
    //     })
    //     .then(response => response.json())
    //     .then(data => {
    //         if (data.distance !== null) {
    //             document.getElementById('resultArea').textContent = `距离:${data.distance}`;
    //         } else {
    //             document.getElementById('resultArea').textContent = '错误:未找到该路线的距离数据';
    //         }
    //     })
    //     .catch(error => {
    //         document.getElementById('resultArea').textContent = '错误:请求失败,请重试';
    //         console.error('请求出错:', error);
    //     });
    // });
    </script>
</body>
</html>

3. 关键说明

  • 下拉框生成:PHP自动从CSV中提取所有唯一的区域编码和名称,动态生成下拉选项,无需手动编写。
  • 两种查询方式:
    • 纯前端查询:适合数据量小的场景,直接把距离数据嵌入页面,响应更快。
    • AJAX后端查询:适合数据量大的场景,避免把所有数据暴露在前端,更安全。
  • 数据安全:使用htmlspecialchars()处理输出内容,防止XSS攻击。

4. 测试示例

当你选择zone1(值为101)到zone4(值为104)时,页面会显示距离:4,和你提供的示例预期一致。

内容的提问来源于stack exchange,提问作者Tore André Rosander

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:18:25