如何在Django

时间:2017-11-06 15:49:57

标签: jquery python json ajax django

我正在处理将数据发布到服务器的Django应用程序。

以下是Python代码段:

def save(request):
    if request.method != 'POST':
        return HttpResponse('Illegal Request')

    print(request.POST.get('dataObj'))

    return JsonResponse({'status':200})

客户端的JQuery:

function submitQuoationClicked()
{
    dataObj = getQuotationInJSON()
    console.log(dataObj)
    token = $("input[name=csrfmiddlewaretoken]").val()
    $.ajax({
     type:"POST",
     url:"/quotations/save",
     data: {
        'csrfmiddlewaretoken': token,
        'dataObj' : dataObj,
     },
     success: function(data){
        if(data.status === 200)
            console.log("Good Work Falak!") //TODO Remove this line, FOR DEBUGGING ONLY
     }
});

function getQuotationInJSON()
{

    var data = {};

    data['title'] = $("#title").val()
    data['companyName'] = $("#company").val()
    data['addressLine1'] = $("#addressLine1").val()
    data['addressLine2'] = $("#addressLine2").val()
    data['city'] = $("#city").val()
    data['country'] = $("#country").val()

    data['date'] = $("#date").val()
    data['number'] = $("#number").val()
    data['validTill'] = $("#validTill").val()


    sections = getItemsData();
    data['sections'] = sections
    return data
}

function getItemsData()
{
    sections = []
    $("tr[id^='section']").each(function(index, element)
    {
        sectionId = $(element).attr('id').split('section')[1]
        name = $(element).find("#sectionName" + sectionId).val()
        section = {}
        section['name'] = name

        //Now get section items
        rowElems = $(".section" + sectionId)
        rows = []
        $(rowElems).each(function(index, row){
        if($(row).attr('id').indexOf('itemRow')>=0)
        {
            description = $(row).find("#description").val()
            quantity = $(row).find("#quantity").val()
            unitPrice = $(row).find("#unitPrice").val()
            margin = $(row).find("#margin").val()

            if(quantity!="" && unitPrice!="" && description!="" && margin!="")
            {
                row = {}
                row['description'] = description
                row['quantity'] = quantity
                row['unitPrice'] = unitPrice
                row['margin'] = margin

                rows.push(row)
            }
        }
    });

    section['items'] = rows;
    sections.push(section)
    });
    return sections
}

JSON对象是一个引用,其中包含一些基本细节。它有一些部分,每个部分都有一个名称和该部分中的项目列表。每个项目都有一些属性。但打印(request.body)返回'无'。如果我打印(request.body),它会打印以下文本:

B' csrfmiddlewaretoken = ph8NQTz5uDtYaTSI5bDVAcdQ0MQtPrYWMMpIFOYP5eqD8urd2wtPRtxypBSnNg1J&安培; dataObj%5Btitle%5D =标题&安培; dataObj%5BaddressLine1%5D =安培; dataObj%5BaddressLine2%5D =安培; dataObj%5Bcity%5D =安培; dataObj%5Bcountry%5D =安培; dataObj%5Bdate%5D =安培; dataObj%5Bnumber%5D =安培; dataObj%5BvalidTill%5D =安培; dataObj%5Bsections%5D%5B0%5D%5Bname%5D = S1&安培; dataObj%5Bsections%5D%5B0%5D %5Bitems%5D%5B0%5D%5Bdescription%5D =嘿&安培; dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bquantity%5D = 2及dataObj%5Bsections%5D%5B0%5D%5Bitems %5D%5B0%5D%5BunitPrice%5D = 9&安培; dataObj%5Bsections%5D%5B0%5D%5Bitems%5D%5B0%5D%5Bmargin%5D = 0'

我试图获得dataObj'来自request.POST.get(' dataObj),但它返回None。

导致问题的原因是什么?

3 个答案:

答案 0 :(得分:0)

在使用Ajax发出POST请求时,请在请求中添加以下标头:

ContentType:application/x-www-form-urlencoded

答案 1 :(得分:0)

POST中的密钥将如下所示:request.POST.get('dataObj[title]')

有关如何在request.body中处理JSON的详细信息,请参阅此问题的答案 Where's my JSON data in my incoming Django request?

答案 2 :(得分:0)

我已经找到了问题所在。我试图传递的对象是Javascript对象,而不是JSON。所以键出现的不是预期的格式。所以,我不得不使用JSON.stringify()方法。

这是更新的代码: // Ajax调用修改为:

$.post("/quotations/save", {csrfmiddlewaretoken: token, 
       data: JSON.stringify(dataObj)}, //Edited here
       function(result){
   if(result.status===200){
       console.log("Good Work Falak!")
   }
   else
   {
       console.log("Failed!")
   }

});