jQuery将带有json主体的get请求发送到restapi
我正在用django和django_rest_框架构建一个网站。 我用httpie测试了restapi 但是当我尝试使用jQuery执行相同的调用时,我得到了一个错误jQuery将带有json主体的get请求发送到restapi,jquery,json,django,rest,django-rest-framework,Jquery,Json,Django,Rest,Django Rest Framework,我正在用django和django_rest_框架构建一个网站。 我用httpie测试了restapi 但是当我尝试使用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/ las
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
或
这个电话有什么问题吗?
我尝试过使用.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构建GET请求时,应该使用
$.param
函数(而不是JSON.Stringify
函数)
$.ajax({
键入:“GET”,
url:“/”,
数据类型:“json”,
processData:false,
数据:$.param({'last_id':1650}),
成功:功能(resp){
控制台日志(resp);
}
});代码>
如果删除contentType
和processData
选项,只需执行data:{last_id:1650},
GET没有正文…它只使用url,会发生什么。因此,没有contentType
这仍然是相同的结果。是否有任何类型的javascript库来发出rest请求?如果删除processData:false
数据将由默认值内部处理$.param()
,谢谢您的评论!此外,GET没有contentType
$.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);
}
});
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)
data: $.param({'last_id' : 1650 }),