首页 > 解决方案 > 如何使用Django将python列表传递给javascript数组

问题描述

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 ,因为它需要一个字典......

标签: javascriptpythonhtmldjangotemplates

解决方案


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);
}

推荐阅读