javascript - 如何使用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 ,因为它需要一个字典......
解决方案
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);
}
推荐阅读
- java - 由于播放保护,应用程序未安装在远程设备上
- java - ListView 未使用 Cursoradapter 填充
- algorithm - 是否有解决网格线交叉点的算法?
- api - 使用带有 Vue.js 的 axios 过滤 API 响应
- aws-sdk - 直接在客户端应用程序中使用 AWS SDK 而不是 api 网关
- python-3.x - 嘿,我不能在我的 pygame 程序中使用 midbottom 函数。每次我运行我的程序时,我都会在左下角看到我的 rect 对象
- computer-vision - 如何导入带注释的图像数据集 Google Colab
- python - J2000坐标转换为ECEF
- drag-and-drop - APEX Dropzone 插件:从 Lotus Notes 拖放不起作用
- tcp - 网络层如何知道它是否必须对数据包进行分段