簡體   English   中英

發布到 phpspreadsheet

[英]POST to phpspreadsheet

我對 phpspreadsheet 有疑問。 我需要將數據傳遞給 php 文件,生成 excel 文件。 我可以用

        window.location.href='pagegeneratingexcel.php?parameter=parvalue';

在生成 excel 的頁面中,我可以輕松檢索 GET 變量。 但是我需要傳遞一些變量,或者 arrays,那么我應該使用 POST 來代替。 我試過 ajax

    postData = { parameter: "parvalue"};


    $.ajax({
        url : "pagegeneratingexcel.php",
        type: "POST",
        data : postData,
        dataType: "json",
        success:function(data){
            console.log(data);
        }
    })

但這給出了500 錯誤 我嘗試生成一個動態表單並提交它......類似於:

let form = $(document.createElement('form'));
$(form).attr("action", "pagegeneratingexcel.php");
$(form).attr("method", "POST");
$(form).css("display", "none");
    
let input1 = $("<input>")
.attr("type", "text")
.attr("name", "parameter")
.val("parvalue");
$(form).append($(input1));
        
form.appendTo( document.body );
        
$(form).submit();

仍然沒有辦法:它給出了500 錯誤

問題似乎與 pagegeneratingexcel.php 文件中的這一行有關:

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("TemplateExport.xlsx");

這就是它停止的地方:這條指令(不過,我的 excel 文件生成需要)似乎與任何類型的 POST 沖突,而一切都與 GET 完美配合:

window.location.href='pagegeneratingexcel.php?parameter=parvalue';

或 - 當沒有數據傳遞時:

window.location.href='pagegeneratingexcel.php';

僅供參考 pagegeneratingexcel.php 類似於

require_once('vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("TemplateExport.xlsx"); 

$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->SetCellValue("A1", "MYVALUES");

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="OUTPUTFILE.xlsx"');
$writer->save('php://output');

我已經自己整理了,無論如何感謝您的評論 CBroe。 問題是它看起來像 window.location.href 方法在結構上與 ajax POST 不同(我仍然忽略為什么)所以正確的方法是使用動態表單,這實際上是我的第二個選擇,但我有忘記 JSON.stringify arrays 阻止它通過它們......

    let form = $(document.createElement('form'));
    $(form).attr("action", "pagegeneratingexcel.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");
    
    let input1 = $("<input>")
    .attr("type", "text")
    .attr("name", "parameter")
    .val("parvalue");
    $(form).append($(input1));
    

    let inputNomiCampiA = $("<input>")
   .attr("type", "text").attr("name", 
   "nomiCampiA")
   .val(JSON.stringify(nomiCampiA));  //this is the point
   $(form).append($(inputNomiCampiA));
    
    
   form.appendTo( document.body );
   $(form).submit();
   $(form).remove();

顯然 pagegeneratingexcel.php 需要 json_decode arrays 才能將它們作為真正的 arrays

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM