如何在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 :(得分: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];
}
}
}
答案 1 :(得分:0)
使用json.loads解决了这个问题:
g_data = json.loads(request.GET.get('json_data'))