AJAX请求数据库 - 下载.csv文件

时间:2016-12-21 21:17:56

标签: javascript ajax postgresql csv export

我有一个调用exportCSV函数的按钮。此函数对我的postgres数据库执行select语句,并通过AJAX请求返回结果。

如何通过浏览器将响应内容作为.csv文件提供给客户端?目前,代码仅在浏览器控制台中提供响应。任何建议将不胜感激。一旦php启动,就会有一个smarthandler类来处理数据库交互。

exportCSV功能

exportCSV: function () {
    var me = this;
    var message = 'Are you sure you want to generate the CSV?';
    var icon = Ext.Msg.QUESTION;

    Ext.Msg.show({
        title: 'Confirm Execution',
        message: message,
        buttons: Ext.Msg.YESNO,
        icon: icon,
        fn: function(btn) {
            if(btn === 'yes') {
                // TODO: Probably should handle an error here.
                Ext.Ajax.request({
                    url: 'data.php',
                    async: true,
                    params: {
                        action: 'export-csv',
                        id: me.currentRecord.data.id,
                        type: 'Carrier'
                    },
                    success: function(response,opts) {
                        var data = Ext.decode(response.responseText);
                        var csvContent = "data:text/csv;charset=utf-8,";
                        data.forEach(function(infoArray, index){
                            dataString = infoArray.join(",");
                            csvContent += index < data.length ? dataString+ "\n" : dataString;
                        });
                        var encodedUri = encodeURI(csvContent);
                        var link = document.createElement("a");
                        link.setAttribute("href", encodedUri);
                        link.setAttribute("download", "carrier_profile.csv");
                        document.body.appendChild(link); // Required for FF

                        link.click(); // This will download the data file named "carrier_profile.csv".
                    }
                });
            }
        }

    });
}

PHP

else if($action == 'export-csv') {
// Create an array of filters.
$parsedFilters = array();
// TODO: Sanitize the properties better.
if(isset($_REQUEST['filter'])) {
    $filters = json_decode($_REQUEST['filter']);
    foreach($filters as $record)
        array_push($parsedFilters,array($record->property => $record->value));
}

// Convert a request for a specific ID into a filter.
if(isset($_REQUEST['id']))
    array_push($parsedFilters,array('id' => $_REQUEST['id']));

$objectHandler = new SmarterHandler($typeDefinition);
$records = $objectHandler->read($type,$parsedFilters);

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=file.csv');

if(count($records) > 0) {
    $record = $records[0];
    $headings = array();
    foreach($record as $key => $value) {
        if(is_scalar($value)) {
            $headings[] = $key;
            echo $key.",";
        }
    }

    echo "\r\n";

    foreach($records as $record) {
        foreach($headings as $key) {
            echo $record[$key].",";
        }

        echo "\r\n";
    }
}

exit();

}

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的内容可以通过accepted answer for this question中的步骤来完成。

假设您的数据格式正确(包括csv数据前的data:text/csv;charset=utf-8),要下载它,您可以创建隐藏链接并模拟点击

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".