2017-01-31 82 views
0

如何在Django View中使用傳遞的值(列表/數組)? 我已經試過這樣的事情:在Django View中傳遞列表或數組(作爲參數)

def to_csv(request): 
    g_data = request.GET.getlist('json_data') 
    g_header = request.GET.get('header') 
    g_info = request.GET.get('info') 
    response = HttpResponse(content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' 

    list_header = [[g_info, '', '', '', '', '', '', ''], 
        ['Municipality', 'Barangay', 'Total Number of Structures', 'Total Not Affected', 'Total Affected', 
        'Low', 'Medium', 'High', 'Total Affected %']] 
    disclaimer = [ 
     'Disclaimer: The information....', 
     '', '', '', '', '', ''] 

    for val in g_data: 
     perc = (val[4]/float(val[2])) * 100 
     st_perc = str(round(perc, 2)) 
     val.append(st_perc) 
     list_header.append(val) 

    list_header.append(disclaimer) 

    writer = csv.writer(response) 
    writer.writerows(list_header) 
    return response 

,並在我的JavaScript代碼中使用AJAX:

function to_csv(json_data, header, info){ 
$.ajax({ 
    url: "/to_csv/", 
    headers: { 
    Accept : "text/csv; charset=utf-8", 
    "Content-Type": "text/csv; charset=utf-8" 
    }, 
    type: "GET", 
    data: { 
     'json_data': json_data, 
     'header': header, 
     'info':info 
    }, 

的問題是,它沒有得到傳遞數據(的G_data

回答

0

通過使用json.loads解決了這個問題:

g_data = json.loads(request.GET.get('json_data')) 
1

這似乎是一個往返發送數據到服務器的浪費,並要求它創建一個CSV,當你可以很容易地在JavaScript本身做到這一點。服務器負載較小,響應速度更快。

假設你的鏈接就像是

<a href="" id="download_link">Download CSV</a> 

然後

function to_csv(json_data, header, info){ 
    var s = "data:text/csv," 
    for (var key in json_data) { 
     if (json_data.hasOwnProperty(key)) { 
      s += json_data[key]; 
     } 
    } 
}