Javascript 在 html 被 hx-get 调用时不执行



我在Django应用程序中加载了以下html:pie_chart.html

{% load i18n %}
<div id="chartcontainer" >
<div style= "width: 400px;" "height: 400px;">
<canvas id="pie-chart"></canvas>
<b>Balance: </b> {{balance}}<br>

</div>
<div>
<h5>Detail group: 
<select name="group" id="group"
hx-get="groupdetail/"
hx-trigger="click changed delay:1s"
hx-target="#groupchart"
hx-include="[name='year']"
hx-swap="innerHTML"
>}
{% for l in labels %}
{% if l == groupcode %}
<option value={{l}} selected>{{l}}</option>
{% else %}
<option value={{l}}>{{l}}</option>
{% endif %}
{% endfor %}
</select>
</h5>
</div>

<div id=groupchart>
{% include 'bar_chart.html' %}
</div>
</div>
<script>
var config_pie = {
type: 'pie',
data: {
datasets: [{
data: {{ data|safe }},
backgroundColor: {{ backgroundcolor|safe }},
label: 'Amount_EUR',
}],
labels: {{ labels|safe }}
},
options: {
responsive: true
}
};

var ctx_pie = document.getElementById('pie-chart').getContext('2d');
window.myPie = new Chart(ctx_pie, config_pie);
</script>

bar_chart.html

{% load i18n %}
<div>
<div style= "width: 400px;" "height: 400px;">
<canvas id="group-chart"></canvas>
<b>Balance: </b> {{groupbalance|safe}} <br>
<p id="data"> her should com the config_bar var</p>
</div>
</div>
<script>
var config_bar = {
type: 'bar',
data: {
datasets: [{
data: {{ groupdata|safe }},
backgroundColor: {{ backgroundcolor|safe }},
label: 'Amount_EUR',
}],
labels: {{ grouplabels|safe }}
},
options: {
indexAxis: 'y',
responsive: true
}
};

var ctx_bar = document.getElementById('group-chart').getContext('2d');

window.myBar = new Chart(ctx_bar, config_bar);
document.getElementById("data").innerHTML = config_bar;
</script>

当bar_chart.html被{% include 'bar_chart.html' %}调用时,脚本被执行,图表被正确显示。

当bar_chart.html被用hx-get="groupdetail/&quot调用的Django视图调用时,脚本不会被执行。显示html,但没有构建图形,因为脚本没有执行。

到现在已经两天了,我在网上搜索这个问题的答案。

如果有人能告诉我为什么会这样,那就太好了。

我试着把html,必须被替换在和没有,改变hx-swap="innerHTML"for hx-swap="outerHTML",但没有改变。

我找到问题所在了。当加载'bar_chart.html'与hx-get我没有定义'backgroundcolor'变量。这个缺失的变量阻止了脚本的执行。

我还将进一步研究如何使用'mariodev'提出的建议。

谢谢你的建议。

最新更新