【发布时间】:2017-03-19 23:26:06
【问题描述】:
我正在使用 django 和 django_rest_framework 构建一个网站。 我用httpie测试了其余的api。
但是当我尝试使用 jQuery 进行相同的调用时,我得到了一个错误。
jquery.min.js:4 GET http://localhost:8000/api/recentposts/?{%22last_id%22:1650} 500 (Internal Server Error)
与httpie的调用如下
http get localhost:8000/api/recentposts/ last_id=1650
或
http get localhost:8000/api/recentposts/ < recent.json
----------------------------
content of recent.json
{
"last_id": 1650
}
我得到了正确的结果。
我在使用 jquery 时尝试过
$.ajax({
type: 'GET',
url: 'http://localhost:8000/api/recentposts/',
contentType: 'application/json',
dataType: 'json',
processData: false,
data: JSON.stringify({ last_id : 1650 }),
success: function(resp){
console.log(resp);
}
});
电话有问题吗? 我试过用 .get 代替 .ajax,还有很多不同的方法来传递 json,但我还没有解决任何问题。
顺便说一下,这是被调用的视图
class RecentPostViewSet(viewsets.ReadOnlyModelViewSet):
'''
ViewSet that displays recent posts after it post id
It needs a JSON file like the following
{
"last_id" : int
}
'''
queryset = Post.objects.all()
serializer_class = PostSerializer
def list(self, request):
recent_feed = Post.objects.filter(hidden=False).order_by('-pub_date').filter(pk__gt=request.data['last_id'])
log.warning("incoming request")
log.warning(dir(request))
log.warning(request.data)
log.warning(request.query_params)
serializer = self.get_serializer(recent_feed, many=True)
return Response(serializer.data)
这是因为 jQuery get 调用无法使用 json 正文执行 get 请求吗?还是我搞错了? 顺便说一句,我使用的是 jQuery 3.1.1
【问题讨论】:
-
如果您删除
contentType和processData选项会发生什么情况,只需执行data: { last_id : 1650 }, -
GET 没有正文...它只使用 url。因此也没有
contentType -
还是一样的结果。
-
是否有任何类型的 javascript 库可以发出休息请求?
标签: jquery json django rest django-rest-framework