使用javascript从数据库获取数据

使用javascript从数据库获取数据,javascript,django,ajax,xmlhttprequest,fetch,Javascript,Django,Ajax,Xmlhttprequest,Fetch,在Javascript函数中,我需要来自数据库的数据 我应该使用什么XMLHttpRequest或fetch()或Ajax* 我尝试了第一个,但我读到的地方很旧,而且fetch()是首选。这是真的吗 我是个初学者,不管怎样,我的file.js: function FilterBy(selezione) { ... var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if

在Javascript函数中,我需要来自数据库的数据

我应该使用什么
XMLHttpRequest
fetch()
Ajax
*

我尝试了第一个,但我读到的地方很旧,而且
fetch()
是首选。这是真的吗

我是个初学者,不管怎样,我的
file.js

function FilterBy(selezione) {
...
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            document.getElementById("test").innerHTML = this.responseText;
        }
      };
      //xhttp.open("GET", "lists/getlistname/?m="+maschio+"&f="femmina+"&n="neutro+"&l="linguaggio+"&i="initial", true);
      //xhttp.open("GET", "/lists/getlistname/?maschio=True", true);
      xhttp.open("GET", "/lists/getlistname/", true);
      //xhttp.send("m="+maschio+"&f="+femmina+"&n="neutro+"&l="linguaggio+"&i="initial");
      xhttp.send("maschio=True&femmina=False&neutro=False&linguaggio=romano&initial=a");
}
我做了一些尝试,但参数没有达到我的观点。我还可以使用url django样式,比如
lists:getlistname

这里是我的
url.py

urlpatterns = [
    ...
    path('getlistname/', views.getlistname, name='getlistname'),
]
def getlistname(request, maschio=True, femmina=True, neutro=True,
                linguaggio='tutti', initial='0'):
    ...
    return HttpResponse('hi')
我的
视图.py

urlpatterns = [
    ...
    path('getlistname/', views.getlistname, name='getlistname'),
]
def getlistname(request, maschio=True, femmina=True, neutro=True,
                linguaggio='tutti', initial='0'):
    ...
    return HttpResponse('hi')
那么,会发生什么?调用视图
getlistname
,但不传递参数(它使用默认值)

*注意:对于使用Ajax,我的意思是:

    $.ajax({type: 'GET',
        url: '/lists/getnamelist/',
        data: {
            maschio: True,
            femmina: True
            ...
        },
        success: function () {
        ...
        }
    });

编辑:最后我使用了$.ajax(),因为据我所知,它效率较低,但更干净

您需要完成服务器端的工作,在视图中使用方法或类。这取决于您的数据库模型。之后,您可以使用javascript获得结果,但仅基于js无法访问数据库

在您的情况下,对于“Hi”消息,可以使用ajax。请告诉我您是否需要数据库中的数据或字符串

对于数据库: 您可以创建一个方法:

def data_get(request):
    if request.method == 'POST':
        data = dataModel.objects.all()
        # you can process data into mylist or another method to do that
    return return render(request, "yoururl.html", {'mylist' : mylist})
然后您可以在html中获取这些数据。你需要为此贴一张表格


当然还有很多其他的方法。

嗨,我想建议您使用类似的方法,它是轻量级的,并且有很多功能,如果您不能向项目中添加库,我认为您应该使用
获取api
我需要数据,但我认为可以做到这一点。我必须回去工作。我已经有了一个可以检索数据的视图,即使我使用GET(可能是大小和安全性,我会在POST中更改),并且我没有检查方法(
if request.method==
)。问题是我的视图不接受随XMLHttpRequest发送的参数。例如,变量
maschio
始终为
True
(默认值),即使我正在发送
False
,您也必须使用post在表单中发送参数。创建一个表单并发布它。