j查询:
$.ajax({
url: '/notify/',
type:'GET',
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
url.py:
url(r'^notify/$', views.notify,name='notify'),
View .py:
from django.http import HttpResponse
from django.http import Http404
from django.http import JsonResponse
def notify(request):
data = {
'is_taken': Notification.objects.all()
}
return JsonResponse(data)
在控制台中调用ajax:
Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)
可能出了什么问题?一切都是正确且存在的。 Django 1.8,jQuery 3.1.0
编辑:Django 错误日志回溯
Internal Server Error: /notify/
Traceback (most recent call last):
File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/TheKotik/djboy/blog/views.py", line 212, in notify
return JsonResponse(data)
File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/http/response.py", line 535, in __init__
data = json.dumps(data, cls=encoder)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/core/serializers/json.py", line 112, in default
return super(DjangoJSONEncoder, self).default(o)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [<Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>] is not JSON serializable
最佳答案
您需要确保您的结果(在您的情况下data
)是json可序列化的,请注意您正在执行'is_take':Notification.objects.all()
,你应该这样做:
from rest_framework.response import Response
from rest_framework.decorators import api_view
@api_view(['GET', ])
def notify(request):
data = {
'is_taken': NotificationSerializer(Notification.objects.all(), many=True).data
}
return Response(data)
并写下 Serializer例如用于通知
的NotificationSerializer
关于jquery - AJAX 调用 Django View 时出现内部错误(restframework 端点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40744156/