Нашёл решение, но оно работает с textarea только. Как сделать, чтобы данные брались из дива?
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Generating files with JS & PHP | Tutorialzine Demo</title>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="assets/css/styles.css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>Generating Files with JavaScript</h1>
<h2><a href="http://tutorialzine.com/2011/05/generating-files-javascript-php/">« Read and download on Tutorialzine</a></h2>
</header>
<form action="./" method="post">
<textarea></textarea>
<a href="#" class="blueButton" id="download">Download</a>
</form>
<footer>Another cool example: <a href="#" id="downloadPage">download this page.</a> <b>To download the source code, visit <a href="http://tutorialzine.com/2011/05/generating-files-javascript-php/">Tutorialzine.com</a></b></footer>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="assets/js/jquery.generateFile.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
download.php
if(empty($_POST['filename']) || empty($_POST['content'])){
exit;
}
$filename = preg_replace('/[^a-z0-9\-\_\.]/i','',$_POST['filename']);
header("Cache-Control: ");
header("Content-type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $_POST['content'];
assets/jquery.generateFile.js
(function($){
$.generateFile = function(options){
options = options || {};
if(!options.script || !options.filename || !options.content){
throw new Error("Please enter all the required config options!");
}
var iframe = $('<iframe>',{
width:1,
height:1,
frameborder:0,
css:{
display:'none'
}
}).appendTo('body');
var formHTML = '<form action="" method="post">'+
'<input type="hidden" name="filename" />'+
'<input type="hidden" name="content" />'+
'</form>';
setTimeout(function(){
var body = (iframe.prop('contentDocument') !== undefined) ?
iframe.prop('contentDocument').body :
iframe.prop('document').body;
body = $(body);
body.html(formHTML);
var form = body.find('form');
form.attr('action',options.script);
form.find('input[name=filename]').val(options.filename);
form.find('input[name=content]').val(options.content);
form.submit();
},50);
};
})(jQuery);
assets/script.js
$(document).ready(function(){
$('#download').click(function(e){
$.generateFile({
filename : 'export.txt',
content : $('textarea').val(),
script : 'download.php'
});
e.preventDefault();
});
$('#downloadPage').click(function(e){
$.generateFile({
filename : 'page.html',
content : $('html').html(),
script : 'download.php'
});
e.preventDefault();
});
});