2016-11-06 36 views
1

我正在用django和django_rest_framework构建一个网站。 我用httpie测试了其余的api。jQuery获取json主体请求到REST 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得到调用不能够做一个json体的GET请求?或者我出错了? 顺便说一下,我使用jQuery 3.1.1

+1

如果去掉'contentType'和'processData'选项,只是做会发生什么'数据:{last_id:1650}' – adeneo

+0

一个GET没有主体。 ..它只使用网址。因此,没有'contentType' – charlietfl

+0

仍然有相同的结果。 – WisdomPill

回答

1

当你建立一个GET请求(而不是JSON.Stringify函数)时,你应该使用$.param函数。

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>

+1

如果你删除了'processData:false',那么数据将在默认情况下由内部的$ .param()处理。 – charlietfl

+0

感谢您的评论! – Dekel

+0

还有一个GET没有'contentType' – charlietfl