javascript - 在 Django 中将页面下载为 JSON
问题描述
我有一个返回格式化 JSON 对象的视图。它需要一个单词列表(在这个项目中标记为“表单”和“引理”),将它们格式化为一个漂亮的字典对象并输出一个 json 页面,然后用户可以保存该页面。
views.py
def search_view(request):
"""
The app revolves around this view, which is also the homepage.
"""
context = {}
if request.method == 'GET':
return render(request, 'search.html', context)
if request.method == 'POST':
checked_A = {}
checked_B = {}
# All lemma keys are of the form {lemma}@{group}.
# All form keys are of the form {lemma}@{group}@{form}.
# The "@" symbol will not appear in any other key.
# Split the key_data into two parts, the lemma/group part
# and the form part. The form part is either [] or [form]
for key in request.POST:
if "@" not in key:
continue
key_data = key.split("@")
(lemma, group), form = key_data[:2], key_data[2:]
if group == "A":
if checked_A.get(lemma):
checked_A[lemma].extend(form)
else:
checked_A[lemma] = list(form)
if group == "B":
if checked_B.get(lemma):
checked_B[lemma].extend(form)
else:
checked_B[lemma] = list(form)
context['query_A'] = checked_A
context['query_B'] = checked_B
return JsonResponse(context, status=200) # <-- the only important part
有没有办法创建一个按钮来直接下载这些数据,而不是让用户去一个单独的页面并保存数据?
解决方案
要实现这一点,您必须简单地向 http 响应对象添加一个附加标头,特别是Content-Disposition: attachment
标头。
在此处查看详细信息:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
推荐阅读
- c++ - 当我尝试在 C++ 中实现深度优先搜索算法时读取访问冲突
- python-3.x - TensorFlow2:ResNet50 - ValueError
- docker - 使用 docker 在虚拟机上监听 SQL 代理周围的活动
- linux - 无法通过 netdata 启动 fping_gateway.plugin
- python - 如何在 django 视图中填写 ModelForm
- android - Firebase 电子邮件格式错误
- r - 如何通过特定 ID 撤消 R 中的累积值?
- node.js - 无法在 AWS Beanstalk 上运行 Nodejs 应用程序
- c - 指针可以随意操纵内存吗?
- python - 片段管理和导航交付应用程序