3

我让 Rails 从菜单中调用 link_to ajax 以将图表动态插入我网站的主要内容区域。我可以看到 html 被正确替换了。但图表没有被加载。

这是我的 application.html.erb 的主要内容部分:

<div id="maincontentcontainer">
    <div id="maincontent">
        <div class="section group">
            <div class="col span_1_of_7">
                <%= render :partial => "shared/menu" %>
            </div>
            <div id="replace">
                <%= yield %>
            </div>
        </div>
    </div>
</div>

这是插入以下部分的 AJAX 调用之后的索引 html:

<div id="replace">
  <div class="col span_6_of_7">
    <section id="infographic">
      <div id="infographicContent">
        <div id="chart" style="min-width: 310px; height: 700px; margin: 0 auto"></div>
      </div>
    </section>  
  </div>
</div>

以下是部分内容:

<div class="col span_6_of_7">
    <section id="infographic">
        <div id ="infographicContent">
            <%= javascript_include_tag "highcharts" %>
            <%= javascript_include_tag "charts" %>
            <div id="chart" style="min-width: 310px; height: 700px; margin: 0 auto"></div>
        </div>
    </section>  
</div>

我的 chart.js 包含所有图表的选项(称为选项),它们可以像这样传入并运行:

$(document).ready(function () {
        $('#chart').highcharts(options);
    });
});

谁能向我解释为什么?我需要做什么?

谢谢。

4

1 回答 1

2

The problem is that you are calling $('#chart').highcharts(options); before the ajax finished. So, it won't find the <div id="chart"> that wasn't inserted yet.


To resolve that issue, you have two options:

  1. Move the chart creation script to the ajax callback, to execute after ajax completion:
 $.get('domain.com/ajax_call?param=value').then(function(response) {
      $("#replace").html(response);
      $('#chart').highcharts(options);
 });
  1. Move the chart creation script to the response html after the insertion of <div id="chart">:
<div class="col span_6_of_7">
    <section id="infographic">
        <div id ="infographicContent">
            <%= javascript_include_tag "highcharts" %>
            <%= javascript_include_tag "charts" %>
            <div id="chart" style="min-width: 310px; height: 700px; margin: 0 auto"></div>
            <script>$('#chart').highcharts(options);</script>
        </div>
    </section>  
</div>

Note: I am assuming that the additional }); in your code was just a question typo/mistake.

于 2015-03-25T17:44:33.710 回答