Created
May 1, 2014 18:06
-
-
Save hidakatsuya/11457774 to your computer and use it in GitHub Desktop.
CSV や Excel 等のエクスポート処理の終了を検知して JavaScript で何かする方法 ref: http://qiita.com/hidakatsuya/items/1b970d17ecb016dddec7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooController < ApplicationController | |
def export | |
csv_data = CSV.generate do |csv| | |
# (CSV データを作る処理) | |
end | |
# exported という名前で cookie を作成 | |
cookies[:exported] = { value: 'yes', expires: 1.minutes.from_now } | |
send_data csv_data, disposition: 'attachment', | |
type: 'text/csv', | |
filename: 'foo.csv' | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>エクスポート</h1> | |
<div id="message"></div> | |
<%= form_tag foo_export_path, id: 'form' do %> | |
<p> | |
<%= label_tag 'year', '出力年度:' %> | |
<%= text_field_tag 'year', 2014 %> | |
</p> | |
<p><%= submit_tag '実行', id: 'button' %></p> | |
<% end %> | |
<%# Cookie を扱いやすくするために jquery.cookie.js を使う %> | |
<%= javascript_include_tag 'jquery.cookie.min.js' %> | |
<script> | |
$('#form').submit(function(e) { | |
// 実行ボタンをロックし、ラベルを "処理中..." へ | |
$('#button').prop('disabled', true).val('処理中...'); | |
var intervalId; | |
// 1 秒間隔で exported cookie をチェック | |
intervalId = setInterval(function() { | |
if ($.cookie('exported')) { | |
// 実行ボタンをアンロック後ラベルを元に戻す | |
$('#button').prop('disabled', false).val('実行'); | |
// 処理が正常に完了した旨のメッセージを表示 | |
$('#message').text('正常に終了しました。'); | |
// ポーリングを停止 | |
clearInterval(intervalId); | |
// フラグをクリア | |
$.removeCookie('exported', { path: '/' }); | |
} | |
}, 1000); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment