在jQuery和PHP中创buildexcel之前显示消息

我在我的公司创build一个Web应用程序。 用户可以点击一个button,并用MySQL数据创build一个csv。

到目前为止这么神。

在jQuery中,当用户点击buttonredirect到:

document.location.href = '/SDR/SDRJSON.php?type=' + id; 

在PHP上创buildcsv文件:

我连接到数据库并创build一个csv文件:

 while($row = $stmt->fetch(PDO::FETCH_NUM)) { array_push($csv, $row); } $fp = fopen('file.csv', 'w'); foreach ($csv as $row) { fputcsv($fp, $row, ';'); } $FileName = 'PEW_'.$CountryCode; fclose($fp); header('Content-Encoding: UTF-8'); header('Content-type: text/csv; charset=UTF-8'); header("Content-Disposition: attachment; filename='".$FileName."'.csv"); header("Pragma: public"); header("Expires: 0"); echo "\xEF\xBB\xBF"; // UTF-8 BOM readfile('file.csv'); 

在button所在的页面上,用户在那里点击,页面开始等待服务器,然后csv文件开始下载。

对于小文件是可以的,因为它是瞬间的。 但对于较大的文件需要10/15秒。 页面等待服务器时是否可以显示消息?

我不认为PHP可以回声,而csv正在做…你可以做的是将“文档形成”和“文档下载”分为两部分。

让Ajax查询要创build的CSV。 并且,当完成时,PHP(文件形成)将回显文件的path。

然后,您可以使用document.location.href到新创build的文件。

我会给代码

AJAX代码

 $('#sample-button').click(function(){ $.ajax({ url : '/SDR/SDRJSON.php?type=' + id, success : function(data){ if(data.url) { var urlToDownload = data.url; alert("File is ready for download"); document.location.href = "http://www.domain.com/file/path/"+data.url; // Make sure data.url has the full path or append the data.url // with some strings to make sure the full path is reflected // into document.location.href ... } else { alert("Something went wrong"); } } }); alert("CSV is being prepared Please wait... "); }); 

documentFormation.php

 while($row = $stmt->fetch(PDO::FETCH_NUM)) { array_push($csv, $row); } $FileName = 'PEW_'.$CountryCode; $fp = fopen($FileName, 'w'); foreach ($csv as $row) { fputcsv($fp, $row, ';'); } fclose($fp); $response = array(); $response['url'] = $FileName; echo json_encode($response); // You can handle rest of the cases where to display errors (if you have any) // Your DocumentFormation PHP Ends here. No need for header() or readFile. 

如果您不希望文件留在服务器上,请将文档href编辑为此PHP传递'path'作为参数

document.location.href = "documentDownload.php?path="+data.url;

documentDownload.php

 $path = $_GET['path']; $filename = end(explode("/" , $path)); header('Content-Encoding: UTF-8'); header('Content-type: text/csv; charset=UTF-8'); //Assuming $filename is like 'xyz.csv' header("Content-Disposition: attachment; filename='".$filename); header("Pragma: public"); header("Expires: 0"); echo "\xEF\xBB\xBF"; // UTF-8 BOM // Reading file contents readfile('Relative Path to File'.$path); // Deleting after Read unlink('Relative Path to File'.$path); // To Delete right after reading