我正在尝试使用ajax构建一个“导出到CSV”系统 这是我的 ajax 调用
$(document).on('click', '#export-csv', function(){
$.ajax({
url: export_url,
type: 'post',
data:{ validations: validations },
dataType: 'json',
cache: false,
timeout: 1000000,
success: function (data) {
var resp = data.response;
console.log(resp);
},
error: function (error) {
console.log(error);
}
});
});
这是我将数组转换为 csv 的 php 代码
public function exportCsvAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$input = $request->getPost();
$response = $this->getResponse();
$file = fopen('php://output', 'w');
foreach ($input['validations'] as $line) {
fputcsv($file, $line, chr(9), '"');
}
fclose($file);
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="validations-' . time() . '.csv"');
return $response->setContent(\Zend\Json\Json::encode(array('response' => true)));
}
return $this->getResponse()->setStatusCode(400);
}
一切正常。我的 ajax 返回成功,但现在我陷入困境......
ajax调用成功后如何下载文件?下一步是什么?
我已经做了研究,但没有发现任何相关和/或有帮助的内容。
提前致谢。
最佳答案
在 ajax 调用中返回 .csv 文件的 URL。然后在您的成功函数中输入:
location.href = url;
就像浏览器不能自然处理的所有文件类型一样,这将导致浏览器下载文件。
关于php - Ajax 和下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33396580/