2015-10-07 124 views
-1

我写了一个脚本,在其中创建CSV文件并将其保存在我的服务器中的目录中。 CSV文件包含来自查询的属性。 整个过程使用Jquery和Ajax单击按钮执行。从服务器下载CSV文件到本地目录

我现在想要做的是能够在本地保存生成的CSV。我发现了类似的问题,但是我还没有找到答案如何创建一个对话框,它将提示客户指定保存文件的位置。

这是我的jQuery代码部分:

var nodeId = 'something'; 
var ajaxurl = 'requestsII/exportNodeData.php', // script to run 
     data = {nodeId:nodeId}; // data to pass 
     $.post(ajaxurl, data, function (response) {  
       //alert(response); 

     }); 

这是我的PHP脚本:

header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=file.csv"); // EDITED 

if ($db) { 
    $stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId'); 
    $stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId)); 

    #$results=$stmt->fetchAll(PDO::FETCH_OBJ); 
    #$json=json_encode($results); 
    #echo($json); 

    $filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv'; 

    $data = fopen($filename, 'w'); 

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     fputcsv($data, $row); 
    } 

    fclose($data); 

} 

echo($data); // EDITED 

的问题是我怎么能下载本地我的PHP脚本中创建CSV文件?

回答

0

毕竟我没有用上面的方法,我做的是,工作正常其更直接:

var ajaxurl = 'exportNodeData.php', // script to run 
       data = {nodeId:nodeId}; // data to pass 
       $.post(ajaxurl, data, function (response) {  
        document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip'; 

       }); 

这是ajax请求,我为了创建CSV文件(它也被压缩)执行。然后我用这条线:

document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip'; 

为了强制下载文件。

1

试试这个代码

header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=file.csv"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 

echo "record1,record2,record3\n"; 

编辑

试试这个代码

if ($db) 
{ 
    $stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS  "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId'); 
$stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId)); 

#$results=$stmt->fetchAll(PDO::FETCH_OBJ); 
#$json=json_encode($results); 
#echo($json); 

$filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv'; 



header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename=".$filename); 


while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    print_r($row); 
} 
} 
+0

我应该把它放在我的PHP脚本? – user1919

+0

我得到一个500服务器错误。 – user1919

+0

你必须添加标题(前两个标题就足够了)并且回显你的数据。如果你有任何进一步问题,请告诉我。 –

相关问题