无需include()及PHP混写JS,实现Chart.js动态获取项目数据
解决方案
方案1:前端AJAX请求时传递ID参数
这是最直接的无侵入方案,不用调整文件结构,只需要让前端在请求data.php时带上当前页面URL中的项目ID:
- 前端提取URL中的ID:在
update.php的纯JS代码里,用URLSearchParams获取当前页面的id参数:
// 从当前URL提取project_id const urlParams = new URLSearchParams(window.location.search); const projectId = urlParams.get('id');
- 修改Chart.js的数据请求:初始化Chart时,把
projectId作为查询参数传给data.php:
fetch(`data.php?id=${projectId}`) .then(response => response.json()) .then(data => { // 初始化Chart.js的逻辑 new Chart(document.getElementById('gantt-chart'), { type: 'bar', // 你的甘特图配置类型 data: data, options: { // 你的自定义配置项 } }); }) .catch(error => console.error('获取甘特图数据失败:', error));
- 改造data.php接收参数:在
data.php中接收id参数,用预处理语句杜绝SQL注入:
<?php // 数据库连接逻辑(替换为你的实际连接代码) $pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password'); // 验证并转换项目ID为整数,避免非法值 $projectId = isset($_GET['id']) ? (int)$_GET['id'] : 0; if ($projectId <= 0) { http_response_code(400); echo json_encode(['error' => '无效的项目ID']); exit; } // 预处理SQL查询,绑定参数防止注入 $stmt = $pdo->prepare("SELECT * FROM your_gantt_table WHERE project_id = ?"); $stmt->execute([$projectId]); $ganttData = $stmt->fetchAll(PDO::FETCH_ASSOC); // 返回标准JSON格式数据 header('Content-Type: application/json'); echo json_encode($ganttData); ?>
方案2:单文件路由拆分(合并data.php逻辑到update.php)
如果想整合成单文件,可在update.php里通过请求参数区分页面渲染和数据接口逻辑,完全避免PHP混写JS:
<?php // 优先处理数据接口请求 if (isset($_GET['action']) && $_GET['action'] === 'get_gantt_data') { // 这里复用原data.php的逻辑 $projectId = isset($_GET['id']) ? (int)$_GET['id'] : 0; if ($projectId <= 0) { http_response_code(400); echo json_encode(['error' => '无效的项目ID']); exit; } $pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password'); $stmt = $pdo->prepare("SELECT * FROM your_gantt_table WHERE project_id = ?"); $stmt->execute([$projectId]); $ganttData = $stmt->fetchAll(PDO::FETCH_ASSOC); header('Content-Type: application/json'); echo json_encode($ganttData); exit; } // 下面是原update.php的页面渲染逻辑,输出纯HTML ?> <!DOCTYPE html> <html> <head> <!-- 引入Chart.js资源 --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <canvas id="gantt-chart"></canvas> <script> // 纯JS提取ID并请求本文件的接口端点 const urlParams = new URLSearchParams(window.location.search); const projectId = urlParams.get('id'); fetch(`update.php?action=get_gantt_data&id=${projectId}`) .then(response => response.json()) .then(data => { new Chart(document.getElementById('gantt-chart'), { type: 'bar', data: data, options: {} }); }); </script> </body> </html>
关键注意事项
- 强制使用预处理语句:绝对不能直接把
$_GET['id']拼入SQL语句,否则会引发严重的SQL注入风险。 - 参数合法性校验:必须验证
id为有效正整数,拦截非法请求。 - 同源策略检查:确保
data.php和update.php在同一域名下,避免CORS跨域错误。
内容的提问来源于stack exchange,提问作者Caitlin O
相关产品推荐
相关产品推荐

