我有一个简单的网页,我通过html按钮在javascript中触发ajax进行数据库查询,调用php脚本来查询数据库。然后,将查询返回的所有结果填入csv文件并下载。
问题是当我检查wireshark捕获时,我可以在HTTP 200 OK数据包中看到包含我需要的所有信息的数据包。但是,我没有下载文件的下载提示。
以下是数据包中的标题:
HTTP/1.1 200 OK
Date: Thu, 06 Jul 2017 00:52:35 GMT
Server: Apache/2.4.6 (Red Hat Enterprise Linux) PHP/5.4.16
X-Powered-By: PHP/5.4.16
Content-Description: File Transfer
Content-Disposition: attachment; filename=data.csv
Content-Length: 2968
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: application/csv; charset=utf-8
Media type: application/csv; charset=utf-8 (2968 bytes)
如果需要任何进一步的信息,请告诉我。
编辑#1 - 添加了AJAX代码:
$.ajax({
url:"export_csv.php", //the page containing php script
data: { userID : "L2Export", 'avc' : avc, 'connType' : connType },
type: "POST", //request type
success:function(result){
console.log("ajax success");
}
编辑#2 - 添加了PHP代码:
$queryStatement = "SELECT * FROM ".$db_record." ".$where;
header("Content-Description: File Transfer");
header('Content-Type: application/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=data.csv");
$output = fopen("php://output", "w");
fputcsv($output, array(<HEADERS ARE HERE>));
$result = mysqli_query($conn, $queryStatement);
//error_log("Here is the statement $queryStatement", 0);
while($row = mysqli_fetch_assoc($result)) {
fputcsv($output, $row);
}
fclose($output);
mysqli_close($conn);
答案 0 :(得分:1)
创建AJAX请求确实从服务器获取资源,但该响应不会触发浏览器下载提示。要在POST请求上提示下载,您必须提交<form>
并正确设置Content-Disposition
标题(您已在PHP中正确完成):
<form method="POST" action="export_csv.php">
<input type="hidden" name="userID" value="L2Export"/>
<!-- other POST data... -->
<button type="submit">Download CSV File</button>
</form>
如果需要,您甚至可以使用JavaScript在事件监听器中动态添加其他隐藏的<input>
字段:
var form = document.querySelector('form[action="export_csv.php"]');
form.addEventListener('submit', function (event) {
var avcEl = form.querySelector('[name="avc"]') || document.createElement('input');
var connTypeEl = form.querySelector('[name="connType"]') || document.createElement('input');
avcEl.type = 'hidden';
avcEl.name = 'avc';
avcEl.value = avc; // get this how you did for the $.ajax()
connTypeEl.type = 'hidden';
connTypeEl.name = 'connType';
connTypeEl.value = connType; // get this how you did for the $.ajax()
// don't worry, these won't error if they're already children of <form>
form.appendChild(avcEl);
form.appendChild(connTypeEl);
});