如果我成功使用Ajax,我无法弄清楚如何使可下载的csv文件可用。我将链接js ajax脚本以及我在Ajax函数中调用的php文件。感谢您的帮助。我将返回Ajax函数的Success函数。我只是不知道如何将我的数据返回为可下载的csv文件。
JS功能:
function popupClick2 (){
var popupObj2 = {};
var c = '0';
var p = '0';
var i = '0';
if (document.getElementById('checkboxC').checked){c = '1'}
if (document.getElementById('checkboxP').checked){p = '1'}
if (document.getElementById('checkboxI').checked){i = '1'}
popupObj2["checkboxC"] = c;
popupObj2["checkboxP"] = p;
popupObj2["checkboxI"] = i;
popupObj2["rangeD"] = $('#rangeD').val();
popupObj2["year"] = $('#year').val();
popupObj2["popupObj"] = '2';
$.ajax({
type: "POST",
dataType: "text",
url: "popupAjax.php",
data: popupObj2,
cache: false,
success: function(data)
{
alert("Success");
//I would like to have the csv file downloadable here.
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
closePopup2();
}
PHP(popupAjax.php)
<?php
$weekEnding = '';
$PHSN = '';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=eWFO-Report.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('Week Ending', 'WN', 'Project Title', 'Project Contact',
'Org No', 'PHSN', 'No', 'Verified By', 'Date Verified',
'Comments', 'Notes'));
/*** connect to SQL DB ***/
$dbe = get_db_connection('db');
$dbe->connect();
/*** connect or Oracle DB ***/
$db = oci_connect('query','pw','server:1521/world');
if (!$db){
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query = "SELECT * FROM db.dbstuff WHERE (STATUS = 'ACTIVE' OR STATUS = 'CLOSED') AND NUMBER <> ' '";
$runQuery = oci_parse($db, $query);
oci_execute($runQuery);
while($row = oci_fetch_array($runQuery, OCI_ASSOC+OCI_RETURN_NULLS))
{
$WFON = $row['NUMBER']."-".$row['ANUMBER'];
$querySQLDB = "SELECT [Verified_By], [Comments], [Notes], [Date_Verified]
FROM dbo.Information
WHERE dbo.Information.Key_ID = '$WFON'
ORDER BY dbo.Information.ID DESC";
$dbe->query($querySQLDB);
$sqlData = $dbe->fetch();
$dateNoTime = str_replace("12:00:00:000AM"," ",$sqlData['Date_Verified']);
fputcsv($output, array($weekEnding, $WFON, $row['TITLE'], $row['NAME'],
$row['ORG'], $PHSNumber, $sqlData['Verified_By'], $dateNoTime,
$sqlData['Comments'], $sqlData['Notes']));
}
echo $output;
?>
答案 0 :(得分:1)
您可以在popupClick2函数中即时添加表单,如:
function popupClick2 (){
...
($('<form/>', {
'id': 'tmpCsvForm',
'action': "popupAjax.php",
'method': 'post'
}).append($('<input />', {
'type': 'hidden',
'name': 'data',
'value': popupObj2
}))).appendTo('body');
$('form#tmpCsvForm').submit().remove();
}