我使用Bootstrap显示页面,其中一些是数据提取。我添加了一个下载按钮,可以打开一个模式对话框,包括日期范围选择器,关闭按钮和下载按钮,以允许下载更大范围的数据。PHP - Bootstrap模式对话框,选择日期,下载CSV - 无法获取浏览器保存文件
模态代码的摘录:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title" id="DownloadModalLabel">Download Data </h3>
</div>
<div class="modal-body">
<form id="download_form" action="api-dl.php" method="get">
<div class="form-group">
<label for="channel-name" class="control-label">Download Period:</label>
<input type="text" name="daterange" value="<?php echo $DownloadDateStart . " - " . $DownloadDateEnd; ?>" />
</div>
<div class="form-group hidden">
<input type="text" id="channel-id" name="channel-id" class="channel-id" value="ha" />
<input type="text" name="site-id" class="site-id" value="<?php echo $SITE; ?>" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="submitForm" class="btn btn-primary" data-dismiss="modal">Download CSV</button>
</div>
再往下,我有一个脚本响应提交按钮:
$(document).ready(function() {
$("#download_form").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "GET",
data: postData,
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#download_form").submit();
});
});
你会注意到,我称之为PHP文件“API - dl.php“提取数据并用CSV文件进行响应。削减到最低限度假一行应答文件看起来像:
header('Content-Disposition: attachment; filename="12345678.csv";');
header('Content-Type: "text/csv"');
header("Content-Length: 32");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
//
echo '"15/10/2016", "12:00", "1.234\n"';
在这一点上我试过很多冲洗,并输出到PHP输出流等。总是让我在我的浏览器检查窗格:
请求报头:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Cookie:PHPSESSID=.....
Host:r .... .net.au
Referer:http://r .... .net.au/site.php?region=Test&site=Test
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.90 Safari/537.36 Vivaldi/1.4.589.11
X-Requested-With:XMLHttpRequest
响应头:
Cache-Control:no-cache, no-store, must-revalidate
Connection:Keep-Alive
Content-Disposition:attachment; filename="12345678.csv";
Content-Length:32
Content-Type:"text/csv"
Date:Sat, 24 Sep 2016 00:53:13 GMT
Expires:0
Keep-Alive:timeout=5, max=100
Pragma:no-cache
Server:Apache/2.4.18 (Ubuntu)
在我看来,看起来这一主题对的,我已经试过1248点的变化。在“响应”选项卡中我看到了回应,我希望:
"15/10/2016", "12:00", "-1.234"
但对我的生活,我不能做一个浏览器下载。
我看到一些Javascript看起来不错,但数据在客户端不可用,它在服务器上的数据库中。
我不能错过许多我认为 - 你认为它可能是什么?
这将使呼叫两个呼叫,其提到的复杂。一个提供URL和另一个打开它,我们知道目标URL。所以我们可以直接给location.href提供开始和结束动画。参考:http://stackoverflow.com/questions/3346072/download-csv-file-using-ajax – Senthil