jQUERY:
$.ajax({
url: '/notify/',
type:'GET',
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
urls.py:
url(r'^notify/$', views.notify,name='notify'),
views.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
答案 0 :(得分:2)
你需要确保你的结果(在你的情况下data
)是json序列化的,注意你正在做'is_taking': 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
Notification