【问题标题】:jQuery get request with json body to a REST apijQuery获取带有json正文的请求到REST api
【发布时间】: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

【问题讨论】:

  • 如果您删除 contentTypeprocessData 选项会发生什么情况,只需执行 data: { last_id : 1650 },
  • GET 没有正文...它只使用 url。因此也没有contentType
  • 还是一样的结果。
  • 是否有任何类型的 javascript 库可以发出休息请求?

标签: jquery json django rest django-rest-framework


【解决方案1】:

您应该在构建 GET 请求时使用 $.param 函数(而不是 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);
    }
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 如果你删除processData: false,数据将默认由$.param()内部处理
  • 感谢您的评论!
  • 另外,GET 也没有contentType
猜你喜欢
  • 1970-01-01
  • 2019-12-01
  • 2016-02-04
  • 2020-07-12
  • 2017-11-25
  • 2019-02-18
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
相关资源
最近更新 更多