使用AJAX时DOMPDF无法下载文件 [英] DOMPDF not downloading file when using AJAX
问题描述
我正在尝试在Laravel项目中使用BarryVdh/DOMPDF代码. 我用打印按钮制作了一个页面,
I'm trying to work with the BarryVdh/DOMPDF code in my Laravel project. I made a page with a print button, with
<a href="/print-facturen" class="btn btn-default printbtn">Print</a>
这正在调用控制器功能:
This is calling the controller function :
public function printFacturen(Request $request) {
$facturen = Factuur::all();
view()->share('facturen', $facturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
这已成功下载PDF文件.
This is successfully downloading the PDF file.
我的路线是:
Route::get('/print-facturen', 'PrintController@printFacturen')->name('print_overzicht_facturen');
但是,我需要一个单选按钮的内容来填充我的PDF. 所以我将href更改为
But, I need the content of a radio button to fill my PDF instead. So I change my a href to
<a href="#" class="btn btn-default printbtn">Print</a>
我添加了一个jQuery函数:
I add a jQuery function :
$(".printbtn").click(function(e)
{
var option = $("input[name='factuur_selectie']:checked").val();
$.ajax({
type: 'POST',
url: 'print-facturen',
data: {"optionID": option}
})
});
我的控制器更改为
public function printFacturen(Request $request) {
$option = $request->get('optionID');
$facturen = Factuur::all();
$searchFacturen = new \Illuminate\Database\Eloquent\Collection();
foreach ($facturen as $factuur) {
if ($option == 1) {
$searchFacturen->add($factuur);
}
else if ($option == 2) {
if ($factuur->voldaan == true) {
$searchFacturen->add($factuur);
}
}
else if ($option == 3) {
if ($factuur->voldaan == false) {
$searchFacturen->add($factuur);
}
}
}
view()->share('facturen', $searchFacturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
我可以成功看到我的optionID,但是不再下载PDF文件...:-(
I can see my optionID successfully, but the PDF file is NOT being downloaded anymore ... :-(
出现POST错误时,我添加了以下路线:
As I got a POST error, I added this route :
Route::post('/print-facturen', 'PrintController@printFacturen')->name('print_overzicht_facturen');
在检查网络时,我看到了:
When inspecting the network, I see this :
对不起,我还不能在这里发布图片:-( ( https://user-images.githubusercontent .com/5870500/32404394-3555952c-c14f-11e7-82c3-2d000d1a2661.png )
SORRY, I'm not allowed yet to post pictures here :-( (https://user-images.githubusercontent.com/5870500/32404394-3555952c-c14f-11e7-82c3-2d000d1a2661.png)
我在做什么错?
最诚挚的问候,
戴维
推荐答案
您需要设置适当的http响应标头:
You need to set proper http response headers:
header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
要做的另一种简单选择是在单选按钮上动态修改链接以获取如下链接:example.org/download?radio=1
Other simple option to do it will be to dynamic modify link on radio click to get link like: example.org/download?radio=1
这篇关于使用AJAX时DOMPDF无法下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!