我有导出 csv 功能,它在 laravel 上运行良好。但是现在我想通过ajax调用导出函数并使用post方法,但是我没有任何反应。我可以从 Laravel Controller 发送一个变量来响应,但不能发送文件下载。
这是我的代码:
route.php
Route::get('/title/show', 'TitleController@show');
Route::post('/title/show', 'TitleController@exportFromDB');
show.blade.php
<script>
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.ajax({
url: "",
type: "post",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
}
})
})
})
TitleController.php:
$dataExport['Oversea'] = $dataOversea;
$this->titleRepository->export('csv', $properties, $dataExport);
TitleRepository.php
public function export($type, $properties, $data)
{
if (in_array($type, self::EXPORT_TYPE)) {
try {
return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {
$excel->setTitle($properties['_title']);
$excel->setCreator($properties['_creator'])
->setCompany($properties['_company']);
$excel->setDescription($properties['_description']);
$excel->sheet('Sheet', function ($sheet) use ($data) {
foreach ($data as $item) {
$sheet->fromArray($item);
}
});
})->export($type);
} catch (Exception $error) {
throw $error;
}
}
}
我该如何修复它们?谢谢!
最佳答案
试试这个-
不要在您的 Controller 方法中编写用于导出的代码,而是将 excel 文件保存在您的公共(public)文件夹中。
您的 Controller 方法应返回文件名。
在您的 ajax 成功时执行此操作 -
location.href = path/to/file/property_title.xls
所以替换你的这一行
->export($type);
与
->store($type, 'public/reports/', true);
关于php - 通过 Ajax 使用 Laravel 导出 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45626173/