【发布时间】: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
});
}
});
}
此代码在浏览器控制台中给我一个错误。请帮忙。谢谢。
【问题讨论】:
-
@Stack 这是错误'POST localhost:8000/listClients 500 (Internal Server Error)' 所以我认为问题出在
return HttpResponse(json.dumps(data), content_type="application/json") -
检查 stackoverflow.com/a/17548578/8150371 或使用 JsonResponse 而不是 HttpResponse
标签: javascript jquery python ajax django