我正在使用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
$.param
构建GET请求时,应使用该函数(而不是JSON.Stringify
函数)。
data: $.param({'last_id' : 1650 }),
$.ajax({
type: 'GET',
url: '/',
dataType: 'json',
processData: false,
data: $.param({'last_id' : 1650 }),
success: function(resp){
console.log(resp);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句