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

使用JS fetch+innerHTML加载动态页面时Chartist图表无法显示问题

问题解决方向:动态加载Chartist图表空白无数据

问题场景

搭建带侧边导航的简易仪表盘,通过PHP动态生成绑定onclick事件的导航项:

<?php
foreach ($nav as $navitem) {
  if($navitem[2]==1){
    echo "<li onclick='" . $navitem[3] . "' class='sidebar-item pt-2' style='cursor:pointer;'>";
    echo "<a class='sidebar-link waves-effect waves-dark sidebar-link' aria-expanded='false'>\r\n";
    echo "<i class='" . $navitem[1] . "' aria-hidden='true'></i>\r\n";
    echo "<span class='hide-menu'>" . $navitem[0] . "</span></a>\r\n";
  }
}  
?>

点击导航时通过JS fetch获取页面内容并插入到pagebody容器:

//JS Function to load dashboard
function navLoadDashboard(){
  fetch("pages/dashboard.php")
  .then((response) => response.text())
  .then((html) => {
      document.getElementById("pagebody").innerHTML = html;
  })
}

仪表盘用Chartist绘制图表,直接访问页面时图表正常显示,但通过上述动态加载方式仅显示空白画布,控制台无报错,所有相关插件已在index页面中引入。


核心原因与解决方向

  • 动态加载的脚本未自动执行
    浏览器不会自动解析执行通过innerHTML插入的<script>标签代码。解决方式:

    1. 将dashboard.php中的Chartist初始化逻辑抽离为全局函数(比如initDashboardCharts()),放在主页面(index)的全局作用域内。
    2. 在fetch回调插入HTML后,手动调用该初始化函数:
      function navLoadDashboard(){
        fetch("pages/dashboard.php")
        .then((response) => response.text())
        .then((html) => {
          document.getElementById("pagebody").innerHTML = html;
          initDashboardCharts(); // 手动触发图表初始化
        })
      }
      
  • DOM元素渲染时机问题
    极端情况下,插入HTML后DOM可能未完全就绪,导致Chartist无法找到目标容器。可通过requestAnimationFrame延迟执行初始化:

    function navLoadDashboard(){
      fetch("pages/dashboard.php")
      .then((response) => response.text())
      .then((html) => {
        document.getElementById("pagebody").innerHTML = html;
        requestAnimationFrame(() => {
          initDashboardCharts();
        });
      })
    }
    
  • 检查图表容器匹配性
    确认dashboard.php中的图表容器(如<div class="ct-chart"></div>)的类名、ID与初始化代码中的选择器完全一致,避免因选择器不匹配导致无法渲染。

  • 避免重复初始化(可选)
    多次点击导航可能重复创建图表实例,可在初始化前销毁旧实例:

    let chartInstance = null;
    function initDashboardCharts(){
      if(chartInstance){
        chartInstance.destroy(); // 销毁旧实例
      }
      // 创建新图表
      chartInstance = new Chartist.Line('.ct-chart', {
        // 图表数据与配置
      });
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:10:18