可通过Ajax下载CSV文件


Downloadable CSV file Via Ajax

如果成功使用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;
?>

您可以在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();
}