dongshan1396 2015-12-01 12:41
浏览 44
已采纳

何时在使用连接到ajax的btn时运行`headers`

I have a button created with HTML.
The button calls a Jquery function on('click')
Now, ajax is triggered to fetch data from PHP.
The PHP script should output a excel file and open a save dialog for the user to download the excel file.

So i have three files: Main PHP, JS and back-end PHP.
If i put the headers in Main PHP, the save dialog appears just as i enter the page. (Not when pressing button)
If i put the headers first off in the "back-end PHP" nothing hapends at all.

So, where should i put the "headers"?
Maby i cannot do it this way?

HEADERS

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"file.xlsx\"");
header("Cache-Control: max-age=0");

HTML Button in Main PHP

<button class="btn btn-default" id="btnExportElementdata"><span class="glyphicon glyphicon-save" title="Spara"></span></button>

JS

//Btn Save
$('#btnExportElementdata').on('click', function(){
    //Fetch selected ObjNr
    objNr = $('#selectObjekt').val();
    //Send objNr to php and fetch elementData
    $.ajax({
        url: '../phpexcel/php/exportElementData.php',
        method: 'POST',
        data: {objNr : objNr},
        success: function(result){
            $('#elementData').append(result);
        }
    })       
})

Back-End PHP

<?php
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");

//Load db connection
require("conf.php");
//Check if usr is logged in
if(empty($_SESSION['user'])){
  header("Location: index.php");
  die("Redirecting to index.php"); 
}

//Check IF post
if(!empty($_POST['objNr'])){
  //Store post in var
  $objNr = $_POST['objNr'];


  /** Error reporting */
  error_reporting(E_ALL);

  //Load phpexcel includes    
  require '../Classes/PHPExcel.php';

  /** PHPExcel_Writer_Excel2007 */
  include '../Classes/PHPExcel/Writer/Excel2007.php';

  // Create new PHPExcel object
  $objPHPExcel = new PHPExcel();

  // Set properties
  $objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
  $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
  $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
  $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
  $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");


  // Add some data
  $objPHPExcel->setActiveSheetIndex(0);
  $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Nr');
  $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Höjd');
  $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Typ');
  $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Längd');
  $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'AV');
  $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Öppningar');

  $objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Vikt');


  //Fetch data from DB
  $query = "SELECT * FROM element WHERE objekt_nr = '$objNr' ORDER BY length(element_nr), element_nr ASC";
  try{
    $stmt = $db->prepare($query);
    $result = $stmt->execute();
  }
  catch(PDOException $ex){
    die("Failed to run query: " . $ex->getMessage());
  }
  //Insert on first row after heading 
  $row = 2;
  while($value = $stmt->fetch()){
    //Set start Column
    $column = "A";

    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['element_nr']);
    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['hojd']);
    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['typ']);
    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['langd']);
    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['avdrag']."");
    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['oppningar']."");

    $objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['vikt']);

    //INCREASE Row Nr
    $row++;
}

// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle($objNr);

// Write file to the browser
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('file.xlsx');

}
else{
  echo 'Välj objektnummer..';
}

All script but save dialog works just fine!
If i Save the file on server it works perfect.
This issue is all about headers!

  • 写回答

1条回答 默认 最新

  • duan1933 2015-12-02 00:19
    关注

    You need to remove those headers from the files.

    You can use ajax if you want but you must return only the link where the file resides and show it in the browser. When the user click on this link a function will be called. You will set the headers in this function which will force the saved file to be downloaded. I hope this will make sense to you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法