简体   繁体   English

在Django中使用Ajax获取对象列表

[英]Get object list with ajax in Django

I'm using ajax in my django aplication, it works well except when I want to get all the registers in a table. 我在django应用程序中使用ajax,它运作良好,除非要在表中获取所有寄存器。 I don't know how to send from my 'ajaxview' to the javascript code and then, how to parse the result. 我不知道如何从我的“ ajaxview”发送到javascript代码,然后解析结果。

Here is my list.html 这是我的list.html

<table>
  <thead>
   <tr>
    <th>id</th>
    <th>Name</th>
    <th>Gender</th>
    <th>Birth date</th>
   </tr>
  </thead>
  <tbody id="clientList">
    <!--Here where I want to put the client list-->
  </tbody>
</table>
<script>
  getAllClients();
</script>

This is my urls.py 这是我的urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from store_app import ajax as ajaxview
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^listClients/$', csrf_exempt(ajaxview.listClients), name='listClients'),
]

This is my ajax.py where I have diferent views than in views.py 这是我的ajax.py ,其中的视图比views.py中的视图不同

def listClients(request):
    data = []
    clientlist = clients.objects.filter(clientstatus=1)
    #Here is where I don't know if I am doing correctly
    #I don't know how to send the client list or if I have to send it as a JSON
    #Please help here
    data.append({'clist':clientlist })
    return HttpResponse(json.dumps(data), content_type="application/json")

The last code actually work for other stuff, but not to send all the data 最后的代码实际上可以用于其他内容,但不能发送所有数据

This is my list.js script 这是我的list.js脚本

funtion getAllClients()
{
  $.ajax(
  {
    type: "POST",
    url: "/getAllClients/",
    data: "",
    success: function(result)
    {
      console.log(result); //Should I have a json object in 'result' variable?
      $.each(result, function(key, val)
      {
        //Here is where I want to parse each object and add to the HTML table
      });
    }
  });
}

This code give me an error in the browser console. 这段代码在浏览器控制台中给我一个错误。 Please Help. 请帮忙。 Thanks. 谢谢。

You have the right idea and depending on your django version, you could be correct. 您的想法正确,并且取决于您的Django版本,您可能是正确的。 For django version <1.7, you have the correct syntax. 对于Django版本<1.7,您具有正确的语法。 For version 1.7 onwards, you should use a JsonResponse as such: 对于1.7版及更高版本,您应该这样使用JsonResponse:

from django.http import JsonResponse

def listClients(request):
    data = []
    clientlist = clients.objects.filter(clientstatus=1)
    #Here is where I don't know if I am doing correctly
    #I don't know how to send the client list or if I have to send it as a JSON
    #Please help here
    data.append({'clist':clientlist })
    return JsonResponse(data)

In your AJAX request in the javascript, the result object will, in fact, be the json that you sent from the backend. 实际上,在javascript中的AJAX请求中,结果对象实际上就是您从后端发送的json。 And then in your .each() method you can add the list to the HTML. 然后在.each()方法中,可以将列表添加到HTML。

While you can use the JsonResponse to solve this problem, I would also recommend looking into setting up django-rest-framework since you are creating, in essence, a rest API and could leverage the django-rest-framework library to make it much easier. 虽然您可以使用JsonResponse解决此问题,但我也建议您考虑设置django-rest-framework,因为您实际上是在创建rest API,并且可以利用django-rest-framework库使其变得更容易。 This would require some overhead to learn but definitely could be useful if you need to make more APIs. 这将需要一些开销来学习,但是如果您需要制作更多的API,则绝对有用。 Documentation is here . 文档在这里

Good luck! 祝好运!

You need to include a csrftoken in your request. 您需要在请求中包含一个csrftoken https://docs.djangoproject.com/en/2.0/ref/csrf/ https://docs.djangoproject.com/en/2.0/ref/csrf/

But also you should be using Class Based Views, and Django Forms to make these kinds of requests. 但是,您也应该使用基于类的视图和Django Forms发出此类请求。

The other option that you have is to use the Django Templating language to insert the data that you want. 您拥有的另一个选项是使用Django模板语言来插入所需的数据。 Simply pass the data into the view's context_data. 只需将数据传递到视图的context_data中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM