PDA

View Full Version : data download function from Grid and Chart



mashiki
2 Mar 2011, 4:44 PM
Download is a function that mounts originally on the server side. However, the method that downloaded from Store on the javascript side was examined this time.

The made sample is two of the following.
Both originals are examples of ExtJS, and changed only a little(add function() and buttons).

I think that the meaning of download from Store is large because the example of Chart displays the data that doesn't exist in the server.

http://www123.ddo.jp/grid/array-grid.html
http://4.bp.blogspot.com/-LMB-1u9KcKw/TWxOtl3btuI/AAAAAAAAACM/hAoEynmqUU0/s320/ss2.png

http://www123.ddo.jp/grid/reload-chart.html
http://2.bp.blogspot.com/-bZEx14RZoMA/TWxPIE0vXNI/AAAAAAAAACU/yxDVLZaELj4/s320/ss1.png

I prepared the following php script that only output POSTed data because I was not able to achieve download only by the client side in the mechanism. I would like you to advise by the comment by all means if there is a method it is possible to do only with around here and javascript.

The php script is enough by three lines. However, it is long for the purpose of the following.
- The degree of freedom of the header is given.
- REFFERER is checked as minimum security.


<?php
if (!isSet($_SERVER['HTTP_REFERER'])
|| !preg_match('#^http://([^:/]+)#',$_SERVER['HTTP_REFERER'],$mch)
|| $mch[1]!==$_SERVER['SERVER_NAME']
) die('Security Error'); // simple security check
foreach ($_POST as $header=>$val) {
if ($header==='body') continue;
header("$header: $val");
}
die($_POST['body']);
?>

The function is the following.


Ext.data.Store.prototype.download = function(fn){
var output=[],o=[],
fld = this.fields;
fld.eachKey(function(key){o.push(key)});
output.push(o.join('\t'));
this.each(function(rec) {
var o=[];
fld.eachKey(function(key){o.push(rec.get(key))});
output.push(o.join('\t'));
});
var form = Ext.DomHelper.append(document.body, {
tag: 'form',
style: 'display:none',
action: 'download.php',
method: 'post',
cn:[{
tag:'textarea',
name:'body',
html:output.join('\n')
},{
tag:'input',
name:'Content-Disposition',
value:'attachment;filename='+'&quot;'+fn+'&quot;'
},{
tag:'input',
name:'Content-Type',
value:'text/tab-separated-values'
}]
});
form.submit();
document.body.removeChild(form);
}

This is a little dirty. Could anyone advise though I want to write smarter?

Thank you.