我正在尝试使用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);
}
});
});
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调用中返回.csv文件的url.然后在你的成功函数中放:
location.href = url;
就像浏览器不自然处理的所有文件类型一样,这将导致浏览器下载文件.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。