发布通过(ajax / javascript)到django视图打印空查询集

时间:2017-02-12 19:43:39

标签: javascript ajax django post xmlhttprequest

如果是jquery,我正在尝试使用更多的vanilla javascript。使用$ .post进行ajax调用我没有问题,但我似乎无法使用vanilla javascript。这是我的ajax电话:

$(document).ready(function () {
    $('#addAssignment').click(function () {
        $('#addAssignmentModal').modal('toggle');
    });

    $('#submitAssignment').click(function () {
        if(checkModal()){
            var assignment = {
                title: $('#newAssignmentTitle').val(),
                type: $('#assignmentSelection').val(),
                date: $('#newAssignmentDate').val(),
                details: $('#newAssignmentDetails').val()
            }

            console.log(assignment);
            submitAssignment(assignment);
        }
    });
});

function submitAssignment(assignment) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            //Do stuff
        }
    };
    request.open("POST", '/data/api/create-assignment/', true);
    request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
    //assignment is equal to: {title: "Title", type: "Homework", date: "02/18/2017", details: "Detais"}
    request.send(JSON.stringify(assignment));
}

当我尝试在我的Djano视图中打印出数据时,它每次都打印出一个空的查询集。

def createAssignment(request):
    if request.method == 'POST':
        print(request.POST) # this prints an empty queryset
        # assignment = Assignments()
        # assignment = request.POST.get('assignment')
        # assignment.save()
        data = {}
        data['status'] = "Success"

        return HttpResponse(json.dumps(data), content_type="application/json")
    else:
        data = {}
        data['status'] = "Data must be sent via POST"

        return HttpResponse(json.dumps(data), content_type="application/json")

如何准备数据并正确接收?

更新:

我能够让这个工作。 ajax调用保持不变。为了在我的django视图中打印数据,我使用了以下代码:

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
print(body)

印刷机构提供以下内容:

  

{'详情':'这里有一些细节','标题':'标题','日期':'02 / 18/2017','类型':'家庭作业'}

1 个答案:

答案 0 :(得分:1)

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
print(body)