当前位置 : 主页 > 网页制作 > JQuery >

jQuery和django-rest-framework-bulk:发送列表

来源:互联网 收集:自由互联 发布时间:2021-06-15
我需要使用 django-restframework-bulk mixins将对象列表发送到视图: class APIPicksView(mixins.ListModelMixin, bulk_mixins.BulkCreateModelMixin, generics.GenericAPIView): def get(self, request, *args, **kwargs): return self.lis
我需要使用 django-restframework-bulk mixins将对象列表发送到视图:

class APIPicksView(mixins.ListModelMixin,
                          bulk_mixins.BulkCreateModelMixin,
                          generics.GenericAPIView):

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        print(type(request.DATA)) /* Should be list */
        if isinstance(request.DATA, list):
            # Custom logic here

在浏览器端,我正在尝试发送一个对象的数组(列表):

var csrftoken = $.cookie('csrftoken');
    var data = [];
    for(var i = 0; i < picks.length; ++i) {
        data.push({pick:picks[i], priority:i, user:null});
    }

    $.ajax({
        type:"POST",
        url: "/api/foo/picks/",
        data: /* How should I format this data? */,
        sucess: function() { alert("Success!"); },
        dataType: "json",
        traditional:false, /* Should this be true? */
        crossDomain:false,
        beforeSend: function(xhr, settings) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });
如果你查看请求标题,你会注意到:

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

这是json数据的不正确类型.

您需要设置正确的内容类型并序列化数据:

$.ajax({
    type: "POST",
    url: "/api/articles/",
    data: JSON.stringify(data),
    sucess: function() { console.log("Success!"); },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    crossDomain:false,
    beforeSend: function(xhr, settings) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
});
网友评论