【问题标题】:Get object list with ajax in Django在Django中使用ajax获取对象列表
【发布时间】:2018-06-26 19:56:15
【问题描述】:

我在我的 django 应用程序中使用 ajax,它运行良好,除非我想获取表中的所有寄存器。我不知道如何从我的“ajaxview”发送到 javascript 代码,然后如何解析结果。

这是我的 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>

这是我的 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'),
]

这是我的 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")

最后一个代码实际上适用于其他东西,但不能发送所有数据

这是我的 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
      });
    }
  });
}

此代码在浏览器控制台中给我一个错误。请帮忙。谢谢。

【问题讨论】:

标签: javascript jquery python ajax django


【解决方案1】:

您的想法是正确的,并且根据您的 django 版本,您可能是正确的。对于

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)

在您的 javascript 中的 AJAX 请求中,结果对象实际上是您从后端发送的 json。然后在您的 .each() 方法中,您可以将列表添加到 HTML。

虽然您可以使用 JsonResponse 来解决这个问题,但我还建议您考虑设置 django-rest-framework,因为您本质上是在创建一个 rest API,并且可以利用 django-rest-framework 库来制作它更容易。这将需要一些开销来学习,但如果您需要制作更多 API,肯定会很有用。文档是here

祝你好运!

【讨论】:

    【解决方案2】:

    您需要在请求中包含csrftokenhttps://docs.djangoproject.com/en/2.0/ref/csrf/

    但您也应该使用基于类的视图和 Django 表单来发出这些类型的请求。

    您拥有的另一个选项是使用 Django 模板语言来插入您想要的数据。只需将数据传递到视图的 context_data。

    【讨论】:

    • OP 在视图上的 urls.py 中使用 csrf_exempt,但我不确定它是否正确实现
    • 在我的 urls.py 我有这个 csrf_exempt(ajaxview.listClients) 所以问题不是 csrf
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2017-12-17
    • 2018-12-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多