Created
April 10, 2015 15:49
-
-
Save carlosrivera/768b0c14e083c1ab423f to your computer and use it in GitHub Desktop.
Ajax file download using an iframe
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
//taken from http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax | |
function ajax_download(url, data) { | |
var $iframe, | |
iframe_doc, | |
iframe_html; | |
if (($iframe = $('#download_iframe')).length === 0) { | |
$iframe = $("<iframe id='download_iframe'" + | |
" style='display: none' src='about:blank'></iframe>" | |
).appendTo("body"); | |
} | |
iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument; | |
if (iframe_doc.document) { | |
iframe_doc = iframe_doc.document; | |
} | |
iframe_html = "<html><head></head><body><form method='POST' action='" + | |
url +"'>" | |
Object.keys(data).forEach(function(key){ | |
iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>"; | |
}); | |
iframe_html +="</form></body></html>"; | |
iframe_doc.open(); | |
iframe_doc.write(iframe_html); | |
$(iframe_doc).find('form').submit(); | |
} |
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
$('#someid').on('click', function() { | |
ajax_download('/download.action', {'para1': 1, 'para2': 2}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment