【发布时间】:2021-11-11 12:38:36
【问题描述】:
我想将一些数据从我的 Python 视图函数传递到使用 HTML 的 JS 脚本。这是我的视图函数
def home(request):
if request.method == 'POST':
params = GameOfLifeForm(request.POST)
if params.is_valid():
starting_grid = get_starting_grid(params.cleaned_data)
to_html = {
'animation': True,
'gameoflifeform': params,
'start_grid': starting_grid,
}
else:
to_html = {
'animation': False,
'warning_msg': 'Something went wrong. Try once again.'
}
return render(request, 'get_animations/home.html', to_html)
else:
form = GameOfLifeForm()
return render(request, 'get_animations/home.html', {'gameoflifeform': form})
我的表单包含四个参数,其中一个名为iterations,这是我想传递给 JS 脚本的那个。此外,我想通过start_grid。
我尝试在我的 HTML 文件中按以下方式进行操作
{{ start_grid | json_script:"start-grid" }}
<script
type="text/javascript"
src="{% static 'js/runGameOfLife.js' %}"
></script>
然后在我的JS脚本中我写了
var startGrid = JSON.parse(document.getElementById("start-grid").textContent);
console.log(startGrid);
完美运行,我在控制台中打印出网格。类似的,我可以从 HTML 中获取 iterations
{{ gameoflifeform.iterations.value | json_script:"iterations"}}
<script
type="text/javascript"
src="{% static 'js/runGameOfLife.js' %}"
></script>
当我尝试将这两个变量添加到我的 JS 脚本中时,它不起作用。
{{ gameoflifeform.iterations.value | json_script:"iterations"}}
{{ start_grid | json_script:"start-grid" }}
<script
type="text/javascript"
src="{% static 'js/runGameOfLife.js' %}"
></script>
如何将多个变量传递到我的 JS 脚本中?最好的方法是什么?
【问题讨论】:
标签: javascript html python-3.x django