【问题标题】:How to pass python list to javascript array using Django如何使用Django将python列表传递给javascript数组
【发布时间】:2020-11-12 13:18:24
【问题描述】:

2020 年 7 月 23 日更新

我有一个 Django 项目,我试图将一个值列表从 python 函数传递到我的“index.html”文件。此值列表来自我的 views.py 文件中的数据库查询

我的意见.py

def index_view(request):
    
    context = {}


    con=sqlite3.connect("db.sqlite3")
    cursor=con.cursor()

    db_query="SELECT distinct product_name from dboinvproduct"

    cursor.execute(db_query)

    result=cursor.fetchall()

    con.close()

    list_of_products = list(itertools.chain(*result)) 
    
    context['product_names'] = list_of_products
    return render(request, 'index.html', context)

然后在我的 index.html 正文中

function loadFunct(){
               var products = "{{product_names|safe}}";
               alert(products);
              }

警报显示以下字符串:

['product a', 'product b', 'product c', 'product d']

这比我以前更接近了。问题是,这是一个看起来像数组的字符串...这意味着这不适用于我的应用程序...我需要它采用数组的形式。

最好的方法是什么?我已经阅读了有关 python 方面的 json_dumps 的信息,但我得到了一个 typeError ,因为它需要一个字典......

【问题讨论】:

    标签: javascript python html django templates


    【解决方案1】:

    json.dumps() 应该接受这样的列表。

    >>> import json
    >>> json.dumps(['a','b'])
    '["a", "b"]'
    

    因此,您可以像这样在视图中预先 jsonify 列表,

    context['product_names'] = json.dumps(list_of_products)
    return render(request, 'index.html', context)
    

    并像这样在模板中使用。

    function loadFunct(){
        var products = {{product_names|safe}}; // Be aware that there are no quotes or double quotes. 
        console.log(products);
    }
    

    【讨论】:

    • 感谢 user3003464,成功了!此功能现已完全正常运行。很高兴!
    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 2012-08-23
    • 2015-11-23
    • 1970-01-01
    • 2016-02-23
    • 2011-04-27
    • 2021-05-15
    • 2012-09-27
    相关资源
    最近更新 更多