私は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
です。私の実際のページでは、ajax経由のデータを使用しています。
$('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
なぜこれにajaxが必要ですか?サーバー側のブラウザに適切なヘッダーを置く限り、ダウンロードのためにリダイレクトされません。 – charlietfl
@charlietflおそらく私はそうではありません。メインページには、ボタンを押すとPHPスクリプトを実行して結果をエクスポートする必要があるというボタンがあります。代替手段は何ですか? – blackandorangecat