php
페이지는 브라우저에서 자동으로 다운로드되는 CSV 파일을 생성합니다. 샘플 데이터가 포함 된 버전입니다.php 및 ajax로 CSV 파일 생성 및 다운로드
<?php
$cars = array(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles'));
//Loop through the array and add to the csv
foreach ($cars as $row) {
fputcsv($output, $row);
}
?>
나는 사용자가 생성 할 수 있도록 ajax
를 사용하여 다른 페이지에서이 작업을 실행할 수 있도록하고 싶습니다/메인 페이지를 떠나지 않고 csv
을 다운로드 할 수 있습니다. 메인 페이지에서 사용중인 JavaScript
입니다. 내 실제 페이지에서 나는 아약스를 통해 오는 데이터를 사용하고있다.
$('button[name="exportCSVButton"]').on('click', function() {
console.log('click');
$.ajax({
url: 'exportCSV.php',
type: 'post',
dataType: 'html',
data: {
Year: $('input[name="exportYear"]').val()
},
success: function(data) {
var result = data
console.log(result);
}
});
});
내가 스크립트를 실행 버튼을 클릭
, 그것은 실행 대신 저장/다운로드csv
으로는 콘솔에 전체 일을 인쇄합니다. 내가 원하는 것을 성취 할 수있는 방법이 있습니까? 실제로 파일을 서버에 저장하고 다시 열지 않아도됩니다.
가능한 중복 : https://stackoverflow.com/q/16086162/2732506 – Alexey
왜 당신이를 위해 아약스를해야합니까? 서버 쪽 브라우저에 적절한 헤더를 넣으면 다운로드를 위해 리디렉션되지 않습니다. – charlietfl
@charlietfl 아마도 그렇지 않습니다. 나는 눌렀을 때 PHP 스크립트를 실행하고 결과를 내보내는 버튼이있는 메인 페이지가 있습니다. 대안은 무엇입니까? – blackandorangecat