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.

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

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流