想請教各位,我在參考別人的範例練習寫網頁(py+dj)
已經把從db篩選出來的資料,呈現在網頁畫面上,如下圖.
網頁畫面
想把這些篩選出來的資料另外下載存檔,但目前當按下載按鈕後,傳給後端是空值 @@
所以檔案會是沒內容,要怎麼把篩選的資料存在按鈕帶過去給後端?
除了jquery的ajax用法,有其他方式可以進行嗎? 或是有什麼修改方式??
謝謝各位
附上程式碼
Views:
def down_file(request):
if request.method == "POST":
sids = request.POST.get("sid")
dfs = Data.objects.filter(cid__in=["sid"]).values_list("sid","name","phone","email","dept")
response = HttpResponse(content_type = "text/csv")
response.write(codecs.BOM_UTF8)
response['Content-Disposition'] = 'attachment; filename = "Report.csv" '
writer = csv.writer(response)
writer.writerow(["編號","姓名","手機","信箱","部門"])
for df in dfs:
writer.writerow(df)
return response
Templates:
{% extends "base.html" %}
{% block headmessage %}查詢系統{% endblock %}
{% block main-content %}
<hr>
<script>
function changesid(x) {
window.location = "/bycid/"+x.value+"/";
}
function changedepart(x) {
window.location = "/bydepart/"+x.value+"/";
}
</script>
<form id="sid" action="/bycid/" method="POST">
{% csrf_token %}
工號查詢:<input name="sid" size="50" placeholder="Search" >
<input id="sid" type="submit" value="查詢">
單位查詢:
<select style="width: 200px;" onchange="changedepart(this)">
<option value=0>請選擇單位</option>
{% for dept in sdepartments %}
<option value={{ dept.id }}>{{ dept.name }}</option>
{% endfor %}
</select>
</form>
<br>
<form action="/down_file/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<button type="button" onclick="window.location.href='/down_file'" >下載檔案</button>
<hr>
以下共顯示{{ num }}筆資料:
<table class="table table-striped table-hover table-xxl text-nowrap">
<tr>
<td>工號</td><td>姓名</td><td>手機</td><td>信箱</td><td>單位</td>
</tr>
{% for c in course %}
<tr>
<td><small>{{c.cid}}</small></td> <!--編號-->
<td><small>{{c.name}}</small></td> <!--姓名-->
<td><small>{{c.phone}}</small></td> <!--手機-->
<td><small>{{c.email}}</small></td><!--信箱-->
<td><small>{{c.dept}}</small></td><!--部門-->
</tr>
{% endfor %}
</table>
{% endblock %}
<form id="sid" action="/bycid/" method="POST">
{% csrf_token %}
工號查詢:<input name="cid" size="50" placeholder="Search" >
<input type="submit" value="查詢">
單位查詢:
<select style="width: 200px;" onchange="changedepart(this)">
<option value=0>請選擇單位</option>
{% for dept in sdepartments %}
<option value={{ dept.id }}>{{ dept.name }}</option>
{% endfor %}
</select>
<input id="btnType" type="hidden" value="查詢">
<button type="button" id='down_file'>下載檔案</button>
</form>
<script>
$(document).ready(function(){
$("#down_file").click(function(){
$("#btnType").val('accepted');
$("#sid").submit();
});
});
</script>
首先,根據上面的回答,推測出幾點
所以解決方案就是,Button 要 preventDefault() 先前事件後再開啟新網頁
const openDownloadPage = (e) => {
e.preventDefault()
window.open(url)
}
document.getElementById('down_file').addEventListener('click', openDownloadPage)