【问题标题】:Update JavaScript with Django view values [duplicate]使用 Django 视图值更新 JavaScript [重复]
【发布时间】:2021-11-07 19:59:13
【问题描述】:

在下面的js文件中

'use strict';
$(document).ready(function() {
    buildchart()
    $(window).on('resize', function() {
        buildchart();
    });
    $('#mobile-collapse').on('click', function() {
        setTimeout(function() {
            buildchart();
        }, 700);
    });
});
function buildchart() {
    $(function() {
        var graph = Morris.Donut({
            element: 'chart-pie-moris',
            data: [{
                    value: 60,
                    label: 'Order'
                },
                {
                    value: 20,
                    label: 'Stock'
                },
                {
                    value: 10,
                    label: 'Profit'
                },
                {
                    value: 5,
                    label: 'Sale'
                }
            ],
            ......

我想更新buildchart() 函数中的值,即我的视图文件函数返回的值。 示例

def order(request):
    a = 'calculated integer value'
    return a

所以我想传入order 函数来替换buildchart() 函数中的60。 我怎样才能做到这一点?请帮助新手

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    在 JavaScript 中使用 Django 变量

    只是,用" "' ' 包围Django 变量。 喜欢:

    <script type="text/javascript"> 
       var a = "{{someDjangoVariable}}";
       var b = "{% url 'someDjangoUrl' %}";
    </script>
    

    如果你想在外部 js 文件中使用访问权限&lt;script&gt; 块内的html 文件中定义变量。 并在外部 .js 文件中访问它,就像 普通的 js 全局变量

    <script type="text/javascript"> 
       var a = "{{someDjangoVariable}}";
    </script>
    <script type="text/javascript" href="{% static 
    'path/to/your_js_file.js' %}">
    // In this file you can have access to the 'a' variable.
    </script>
    

    【讨论】:

    • 我正在使用外部 JavaScript 文件。所以JavaScript代码不在我的html文件中
    • 更新了答案。
    • 我无法在外部 js 文件中访问它
    • 你是如何组织你的脚本文件的?
    • 在我的html中,我用&lt;script src="{% static 'js/pages/dashboards_ecommerce.js' %}"&gt;&lt;/script&gt;引用了js文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多