Laravel:Maatwebsite 3.1 using jquery

3j86kqsm  于 2023-06-29  发布在  jQuery
关注(0)|答案(1)|浏览(105)

我们升级了我们项目的laravel版本,一些软件包已经贬值(maatwebsite),所以我们需要升级到最新版本并重新编码导出,但我们有一个错误。
给予一个简短的背景。下面是布局。

用户应在点击按钮之前选择日期、类型和客户。在这一部分我们使用了jquery/ AJAX

** AJAX **

if ( $('#sale-journal-export-csv').length > 0 ) {
            $('#sale-journal-export-csv').submit(function(e){
                $("input[name='customer_id[]']").remove();
                $("input[name='csv_default']").remove();
                var form = this;  
                var rows_selected = $('#get-customers-export-csv').DataTable().column(2).checkboxes.selected();
            // Iterate over all selected checkboxes
                $.each(rows_selected, function(index, rowId){
               // Create a hidden element 
                        $(form).append(
                           $('<input>')
                              .attr('type', 'hidden')
                              .attr('name', 'customer_id[]')
                              .val(rowId)   
                        );
                });
                var formData = $(form).serialize();
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                })
                $.ajax({
                    url: '/reports/sales-journal/exportCSV',
                    type: "POST",
                    data: formData,
                    xhrFields:{
                        responseType: 'blob'
                    },
                    beforeSend: function() {
                        $('.export-csv-button').attr('disabled', 'disabled');
                        $('.loader').show();
                        var span = document.createElement("span");
                        span.innerHTML = '<span class="loading-animation">LOADING...</span>';
                        swal({
                            content: span,
                            icon: "warning",
                            buttons: false,
                            closeOnClickOutside: false
                        });
                    },
                    success: function(response) {
                        if (response) {
                            let src = window.URL.createObjectURL(response);
                        }
                    },
                    complete: function() {
                         $('.export-csv-button').removeAttr('disabled');
                    }
                });
                e.preventDefault();
                return false;
            });
        }

控制器

public function exportCSV(Request $request)
    {
        $data                                               = $request->all();
        $data['csv_name']                                   = date('YmdHis-').'sale-journal';
        return new SaleJournalExport($data);
        // return (new SaleJournalExport($data))->download('sales-journal.csv');
        // return Excel::download(new SaleJournalExport($data), 'sales-journal.csv', \Maatwebsite\Excel\Excel::CSV);

    }

SaleJournalExport Controller

function __construct($data) {
    $output = [];

    $title = ['SALES JOURNAL'];
    
    $output[] = array_values($title);

    $data['company_name']    = UserModel::getCompanyDetails(Auth::user()->company_id);
    if(isset($data['csv_default'])){
        $data['start_date']      = $data['company_name']->accounting_period_start;
        $data['end_date']        = $data['company_name']->accounting_period_end;
        $data['customers']       = CustomerModel::getActiveCustomers();
        $sales                   = SaleJournalModel::getSalesByToday($data['company_name']);

    }else{
        $sales                   = SaleJournalModel::generalFilterAll($data);
    }

    $title6                      = [$data['company_name']->company_name];
    $output[]                    = array_values($title6);
    $date = 
      [
        date('F d, Y', strtotime($data['start_date'])). ' to ' .date('F d, Y', strtotime($data['end_date'])),
      ];
      
      $output[] = array_values($date);
   
    $space = 
    [
        ''
    ];
    $output[] = array_values($space);

    // DETAILS HEADER
    $header1 = 
    [
        "SI/OR No.","Sales Date","Document Reference","Customer","Status","Sales Amount","VAT Amount","Net of VAT","WHT Amount","Amount Due"
    ];

    $output[] = array_values($header1);

        if ($sales){
            foreach($sales as $index => $sale){
                $number                      = ($sale->sale_tag == '0') ? 'SI-'.$sale->number : 'OR-'.$sale->number;
                $table1[] = 
                [ 
                    $sale->number,
                    date('M d, Y',strtotime($sale->date_delivered)),
                    $sale->document_reference,
                    GlobalModel::getSingleDataTable('customers',$sale->customer_id)->name,
                    $this->checkStatus($sale->status),
                    ($sale->total_vat + $sale->total_net_of_vat),
                    $sale->total_vat,
                    $sale->total_net_of_vat,
                    $sale->total_wht,
                    $sale->total_amount_due
                              
                ];
                
            }
        } else {
            $table1[] = 
                [   
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                ];
        }

        $output[]   = array_values($table1);

        $space = 
        [
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
        ];

        $output[]   = array_values($space);

        $footer = [];
        if ($sales){
                $footer = 
                [
                    '',
                    '',
                    '',
                    "",
                    'Grand Total',
                    // $sales->whereNotIn('status_id',[13])->sum('total_amount'),
                    // $sales->whereNotIn('status_id',[13])->sum('discount'),
                    // $sales->whereNotIn('status_id',[13])->sum('vat_amount'),
                    // $sales->whereNotIn('status_id',[13])->sum('amount_due'),
                ];
        }else{
            $footer = 
            [
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
            ];
        }
        
       

        $output[]   = array_values($footer);
      
        $this->collection = collect($output);
 
}

public function collection()
{
    return $this->collection;
}

正如您在SaleJournalExport CSV中看到的,我们操作了数据,然后将值作为集合返回。
我们遇到了一个错误“The Response content must be a string or object implementing __toString(), \"object\" given.”。
我们已经尝试了我们在互联网上搜索的东西,但它不起作用。
问:如何使用jquery/ AJAX 导出到csv?

ibrsph3r

ibrsph3r1#

我能弄明白。我所做的是

var binaryData = [];
binaryData.push(response);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))
link.download = 'sales-journal.csv';
link.click();

相关问题