题意:下载文件并跳转到新页面的按钮
问题背景:
How do I enable my button to download and redirect to a new page? I have tried many code combination but it just downloads and does not redirect
如何使我的按钮能够下载文件并跳转到新页面?我已经尝试了很多代码组合,但它只是下载文件而不进行跳转。
<div class="banner">
<h3>Download your file:<br> {{ filename }}</h3>
<div>
{% csrf_token %}
<form action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<button onclick="openTab()" class="btn btn-primary w-20" id="myBtn" tabindex="4">Download PDF
</button>
</form>
</div>
</div>
<script>
function openTab() {
window.open('home');
}
</script>
问题解决:
You could try something like this to ensure both downloading the file and redirecting to a new page are achieved. The button click that already triggers download and then you can register a brief delay using JavaScript to redirect to your desired page:
你可以尝试这样做来确保既下载文件又跳转到新页面。按钮点击会触发下载,然后你可以使用JavaScript注册一个短暂的延迟来跳转到你的目标页面:
<div class="banner">
<h3>Download your file:<br> {{ filename }}</h3>
<div>
{% csrf_token %}
<form id="downloadForm" action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<button type="button" class="btn btn-primary w-20" id="myBtn" tabindex="4" onclick="downloadAndRedirect()">Download PDF</button>
</form>
</div>
</div>
<script>
function downloadAndRedirect() {
// Submit the form to trigger the download
document.getElementById('downloadForm').submit();
// Redirect after a short delay to allow the download to start
setTimeout(function() {
window.location.href = 'home'; // Change 'home' to your desired redirect URL
}, 1000); // Adjust the delay time as necessary
}
</script>