在jquery和PHP中创建excel之前显示消息


Display message before creating excel in jquery and PHP

我正在公司创建一个web应用程序。用户可以点击一个按钮,然后用MySQL数据创建一个csv。

到目前为止,上帝。

在jquery中,当用户点击按钮时,它会重定向到:

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

在PHP上创建csv文件:

我连接到数据库并创建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');

在按钮所在的页面上,用户单击该按钮,页面开始等待服务器,然后csv文件开始下载。

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

我认为在制作csv时PHP不能回显。。。您可以将"文档形成"answers"文档下载"分为两部分。

让Ajax对要生成的CSV进行查询。完成后,PHP(文档形成)将回显文件的路径。

然后,您可以使用document.location.href新建文件。

我会给出代码

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编辑为This 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