如何将字典从视图传递到模板javascript

时间:2019-05-10 16:16:29

标签: javascript dictionary django-templates django-views display

尝试将每个检查项目的计算值作为字典从视图发送到链接到某些js的results.html模板。如何将该字典发送到html模板,然后发送到js?

我认为可能的复杂之处在于onclick事件发生在currency.html上,并且在script_currency.js中调用的函数随后进入视图进行计算,并以result2 {}的形式返回到另一个模板:results.html但是要呈现这些内容,仍保留在script_currency.js点击功能中。但是results {}也无法进入results.html。

so curency.html-> script_currency.js-> views.py-> results.htmls-> script_currency.js-> results.html上的表。

我将字典放在上下文中,然后放在上下文之外,以在views.py中呈现。我尝试创建一个新模板以使其呈现,因为我将字典发送回同一模板而不刷新。仍然没有喜悦。

views.py-(我从calc()函数获得了results2 {})

def substancesChecked(request):
    request.POST.get('checkbox')
    curArr = json.loads(request.POST['checkbox'])
    user_results = countryCur.objects.filter(user=request.session['user'])
    username = request.session['username']
    results2 = calc(curArr,user_results, username)
    print(results2)
    context = {"username": username, "results2": results2}
    return render(request, 'main_app/results.html', context=context)

results.html-新模板

<script src="{% static "main_app/js/script_currency.js" %}"></script>

   <title>Currency Analysis</title>
   <script type="text/javascript">
      var results2 = "{{ results2 }}";
      console.log(results2);
   </script>

script_currency.js

console.log(results2);

我希望:{GBR:“ 25”,USD:“ 35.58”}

相反,我得到的是result2变量,未定义,并且错误在currency_script.js中

results.html中没有错误,因为即使views.py函数将其返回到result.html,我也不确定是否正在读取它,因此也许该变量未从results.html传递回js。脚本

0 个答案:

没有答案
相关问题