jQuery AJAX请求主体为空。 (Docker内的Django REST)

时间:2019-03-07 17:40:43

标签: javascript python ajax django

使用/ static目录中的JS加载模板index.html。

Javascript(app.js):

    var obj = new Object();
    obj.startTime = "123";
    obj.endTime = "456";
    console.log("fetchNext "+JSON.stringify(obj));
    var data1 = {"name":"John Doe"}

    $.ajax({
        url:"http://localhost:8000/api/time/",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(obj),
        success: function(data){

            console.log(data);
        }
    });
}

正在使用Django REST API,但正文为空。

class QueryTime(APIView):
    def get(self, request, format=None):
        data = "false"
        jsonstr = request.body.decode('utf-8')
        # jsonstr is empty.

我在这里做错了什么?我已经安装了CORS,并尝试对其进行修复,但没有运气。我得到这些结果。

web_1  | [07/Mar/2019 17:36:52] "GET / HTTP/1.1" 200 314
web_1  | [07/Mar/2019 17:36:52] "GET /static/app.js HTTP/1.1" 304 0
web_1  | 
web_1  | [07/Mar/2019 17:36:52] "GET /api/time/?{%22startTime%22:%22123%22,%22endTime%22:%22456%22} HTTP/1.1" 200 7

不确定这些状态码代表什么。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

我看到您的api很奇怪,所以我这样工作

class MODELAPI2(viewsets.ModelViewSet):
    queryset = MyModel.objects.none()
    serializer_class = MyModel_Serializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = MyModel_Filter
    permission_classes = (IsAuthenticated,)


    def get_queryset(self):

       param1 = self.request.query_params.get('param1')
       param2 = self.request.query_params.get('param2')
       argumentos = {}
        if param1 != '':
            argumentos['param1'] =param1
        if param1 != '':
            argumentos['param2'] = param2
       query = Mymodel.objects.filter(**argumentos)
       return query

和ajax。 method:"GET", data:{'param1':param1,'param2':param2}