【发布时间】:2021-06-27 17:15:18
【问题描述】:
我正在使用一个简单的视图来呈现一个“index.html”页面,并在上下文变量中传递一个 JSON。
def index(request):
"""Homepage. Calls are made to other classes from here."""
ytv = YoutubeVideos()
user = request.GET.get('user', '')
videos = {'name': 'filler data here'}
if user != '':
videos = ytv.get(request=request, channel_data=1)
print(videos)
return render(request, 'index.html', context=videos)
return render(request, 'index.html', context=videos)
我已经确认它正在通过第一次返回,视频上下文包含 JSON 数据。它正在控制台中打印。
我还有 index.html 文件,其中包含:
...
{{videos|json_script:'name'}}
<script>
'use strict';
var videos = JSON.parse(document.getElementById('name').textContent);
...
我尝试了几种在 Javascript 中获取 JSON 数据的方法,包括:
<input type="hidden" id="myVar" name="videos" value="{{ videos }}">
然后以这种方式在javascript中获取值,
var myVar = document.getElementById("myVar").value;
问题是当 html 被渲染时它变成了这个(Source 的截图):
基本上,该变量在渲染时看起来并不存在。 任何帮助将不胜感激。
【问题讨论】:
标签: javascript python json django django-templates