javascript - 从现有的 sqlite DB 中获取数据到网页中
问题描述
我有创建 SqlLite DB 的桌面应用程序。
我想使用这些数据在本地静态网页上制作报告。但是我不确定如何连接到现有数据库 - 我知道这存在安全问题。
这对 JavaScript 可行吗?我该怎么做呢?
解决方案
一种选择是从模板中传递数据,如下所示:
def index(request):
# Calculate your precious data here, for example using the django.core.serializers class:
data = serializers.serialize('json', FooModel.objects.all())
return render(request, 'templates/index.html', {'data': data})
然后在你的templates/index.html
你可以做这样的事情:
<script>
window.data = {{data|default:"{}"|safe}};
</script>
检查安全过滤器。
这样,您可以通过初始请求从后端到前端获取所有数据,而无需创建任何其他请求,或直接使用 JS 与您的数据库通信。
另一种选择是使用fetch
:
您可以创建一个视图(您可以使用 Django REST 框架,但这取决于您尝试使用它的目的,无论如何主要思想保持不变):
from django.http import HttpResponseNotAllowed, JsonResponse
from django.core import serializers
from .models import FooModel # for example
def myview(request):
if request.method != "POST":
return HttpResponseNotAllowed(['POST'], "Only POST is allowed to this URL.")
# Get your precious data, let's use the same example as before:
data = serializers.serialize('json', FooModel.objects.all())
return JsonResponse(data)
将其注册到您的urls.py
:
urlpatterns = [
...
path('api/retrievepreciousdata', views.myview),
...
]
然后我们可以使用fetch
它来检索它:
fetch("/api/retrievepreciousdata", {
method: "POST",
headers: {
//For CSRF protection:
//I use `js-cookie` to get the cookies, it's up to you really
"X-CSRFToken": Cookies.get("csrftoken"),
"X-Requested-With": "XMLHttpRequest",
},
}).then(response => {
if(!response.ok) {
console.log("Dang it, the response isn't OK... Response code is", response.status);
}
return response.json()
}).then(json => {
console.log("I did it! My precious data is:", json);
}).catch(e => {
console.log("Dang it, something went wrong while retrieving my precious data:", e);
});
推荐阅读
- r - 如何转换 DATE 列并显示每个国家/地区的 total_cases?
- python - 比较两个目录的测试功能
- authentication - 如何向公司 Active Directory 提供 Google Cloud Run 网站的访问权限?
- wpf - 为什么 DbConnectionStringBuilder 后代会如此彻底地破坏属性网格绑定?
- bash - 使用 bash 在特定列中提取具有特定值的行
- java - 如何构建包含 JAXB/Moxy 适配器的项目
- c# - 弹丸不移动,也不从玩家开始(Unity 2D / C#)
- typescript - 网格数据不显示
- javascript - 默认蜂鸣/叮/警告/警报/嗡嗡声/无声音的 Web API
- angular - 如何在按钮上选择后显示日期