2015-07-05 29 views
1

我想渲染兩個不同的HTML樣本,並將其作爲對ajax請求的響應發回。如何在html中將兩個變量作爲JSON發送給Django?

我有我的看法是這樣的:

def getClasses(request): 
    User = request.user 
    aircomcode = request.POST.get('aircompany_choice', False) 

    working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode) 
    economy_classes = working_row.economy_class 
    business_classes = working_row.business_class 

    economy = render_to_response('dbmanager/classes.html', {"classes": economy_classes}, content_type="text/html") 
    business = render_to_response('dbmanager/classes.html', {"classes": business_classes}, content_type="text/html") 

    return JsonResponse({"economy": economy, 
        "business": business}) 

有了這個,我得到的錯誤:

在0x7f501dc56588

django.http.response.HttpResponse對象不是JSON序列化」

我怎樣才能完成我的任務?

在js當我得到響應我想插入接收的HTML到corespoding塊。像這樣:

$.ajax({ # ajax-sending user's data to get user's classes 
    url: url, 
    type: 'post', 
    data: {"aircompany_choice": aircompany_choice}, # send selected aircompanies for which to retrieving classes required 
    headers: {"X-CSRFToken":csrftoken}, # prevent CSRF attack 
}).done (result) -> 
    add_booking_classes.find(".economy-classes").children(":nth-child(2)").html(result["economy"]) 
    add_booking_classes.find(".business-classes").children(":nth-child(2)").html(result["business"]) 
+0

在JSON你不應該發送HTML,它是一個不錯的辦法...... – madzohan

回答

2

嘗試Django的render_to_string

economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes}) 
business = render_to_string('dbmanager/classes.html', {"classes": business_classes}) 

render_to_string()負荷的模板,呈現它,然後返回結果字符串。然後,您可以將這些結果字符串作爲JSON發送。現在

你的最終代碼變成:

from django.template.loader import render_to_string 

def getClasses(request): 
    User = request.user 
    aircomcode = request.POST.get('aircompany_choice', False) 

    working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode) 
    economy_classes = working_row.economy_class 
    business_classes = working_row.business_class 

    economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes}) 
    business = render_to_string('dbmanager/classes.html', {"classes": business_classes}) 

    return JsonResponse({"economy": economy, 
        "business": business}) 
0

您可以在您的上下文中發送一個,並在您想要呈現的位置發送一個。顧名思義,

1

render_to_response是用於呈現響應。你不想這樣做;你想渲染兩個模板,並將它們放入JSON響應中。所以使用render_to_string

相關問題