发送ajax请求到laravel控制器下载pdf

时间:2018-01-24 12:24:41

标签: javascript php jquery ajax pdf

我有一个带有复选框列的表,当点击某个按钮时,我发送带有ajax请求的复选框给控制器,以便在制作后下载pdf文件,但不幸的是它没有触发下载盒子。我希望你帮助我。

我的Ajax:

<script>
$(document).ready(function()
{
$(document).on('click', '#minvoice', function(event)
{
    //var alert = confirm('Are You Sure?');
    var checkedValues = $('#chkbx:checked').map(function() {
        return this.value;
    }).get();

    $.post('{{route('payments.multiple_invoices')}}', {'checkboxs' : checkedValues, '_token' : $('input[name=_token]').val() }, function(data){
        console.log(data);
    });

});
});
</script>

我的控制器:

public function multiple_invoices(Request $request)
{
    if ($request->isMethod('post')) 
    {   
        //export invoice
        $requestData[] = $request->checkboxs;
        $filenamepdf = public_path().'/export/invoices/multiple_invoices.pdf';
        $data = self::getMulInvoiceData($requestData);
        PDFHelper::export($data, $filenamepdf, true);
        return Response::download($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', []);
    }
}

public static function getMulInvoiceData($requestData)
{
    $payments = UnitPayment::whereIn('id', $requestData)->get();
    return View::make('payments.mulInvoice', compact('payments'));
}

我的观点:

<td><input id="chkbx" type="checkbox" value="{{ $payment->id }}" /></td>

MulInovices.blade.php:

@foreach($payments as $payment)
<div align="left" style="text-align: left;"><b>payment : {{$payment->id}}  </b></div>
@endforeach

我的路线:

Route::any('payments/multiple_invoices', ['uses' => 'PaymentsController@multiple_invoices','as' => 'payments.multiple_invoices']);

我希望你能告诉我如何让它发挥作用。谢谢

1 个答案:

答案 0 :(得分:0)

尝试更改

return Response::download($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', []);

return Response::download($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', ['Content-Type' => 'application/pdf']);

(差异是下面的代码被添加到Response :: download的第三个参数[])

'Content-Type' => 'application/pdf'

如果您使用的是Laravel 5+,则可以使用以下代码

response()->($filenamepdf, 'Multiple_invoice_'.date('Y-m-d').'_'. time().'.pdf', ['Content-Type' => 'application/pdf']);

我们所做的是添加标题以将响应识别为pdf文件。