gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:21:18 24 4
gpt4 key购买 nike

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

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

导出CSV函数

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();

最佳答案

我认为您正在寻找的可以通过执行 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".

关于javascript - 对数据库的 AJAX 请求 - 下载 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com