php 使用 ajax 调用下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17350992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a file with an ajax call
提问by John Ng
I am using PHPExcel to read an excel template, populate the data, and ask the user to download the file.
我正在使用 PHPExcel 读取 excel 模板,填充数据,并要求用户下载文件。
generate_excel.php
生成_excel.php
$objPHPExcel = PHPExcel_IOFactory::load("./template.xlsx");
//populate data ...
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
When I open generate_excel.php directly from the browser, the result file is downloaded. But if I make an ajax call to the generate_excel.php, I don't get the download prompt. Using chrome developer tools, I can see from the Network tab that the ajax call was successfully completed and a bunch of random characters is seen in the response data. I'm assuming that is the excel object.
当我直接从浏览器打开 generate_excel.php 时,会下载结果文件。但是如果我对 generate_excel.php 进行 ajax 调用,我就没有得到下载提示。使用chrome开发者工具,从Network选项卡可以看到ajax调用成功完成,在响应数据中看到一堆随机字符。我假设那是 excel 对象。
Does anyone know how I can achieve the download excel feature using ajax? I don't want to refresh the page. When the user clicks on the "export" button, there should be an ajax call to the php file and prompt the user to download.
有谁知道我如何使用ajax实现下载excel功能?我不想刷新页面。当用户点击“导出”按钮时,应该会有php文件的ajax调用,提示用户下载。
Thanks!
谢谢!
采纳答案by John Ng
Found a way to do this, although I'm not sure if this is an ideal approach.
找到了一种方法来做到这一点,虽然我不确定这是否是一种理想的方法。
I added a hidden iframe in the page. When the ajax call returns, it returns the url of the created data. I used javascript to redirect the iframe to that url which automatically triggers the download action.
我在页面中添加了一个隐藏的 iframe。当ajax调用返回时,它返回创建数据的url。我使用 javascript 将 iframe 重定向到自动触发下载操作的 url。
回答by maozx
I looked for ways to pass JSON data with ajax to PHP and return an excel file (MySQL and PHPExcel) for the user to save. I looked around and put some pieces together, hope it can help someone:
我寻找方法将带有 ajax 的 JSON 数据传递给 PHP,并返回一个 excel 文件(MySQL 和 PHPExcel)供用户保存。我环顾四周,把一些碎片放在一起,希望它可以帮助别人:
jQuery:
jQuery:
$("#exportBotton").on("click",function(event) {
event.preventDefault();
// create json object;
str_json = JSON.stringify({"key01":val01, "key02":val02, "key03":val03});
$.ajax({
type: "post",
data: str_json,
url: "../../includes/dbSelect_agentFormExport.php",
dataType: "json",
success: function(output){
// output returned value from PHP t
document.location.href =(output.url);
}
});
});
PHP:
PHP:
$str_json = file_get_contents('php://input');
$objPHPExcel = new PHPExcel();
// here i populated objPHPExcel with mysql query result.....
function saveExcelToLocalFile($objWriter){
// make sure you have permission to write to directory
$filePath = '../tmp/saved_File.xlsx';
$objWriter->save($filePath);
return $filePath;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = array(
'success' => true,
'url' => saveExcelToLocalFile($objWriter)
);
echo json_encode($response);
exit();
回答by David Jashi
Not everything should be done with AJAX. Sometimes plain old HTML is more suitable for a job. I guess your button has a
tag? Why won't you do something like this
并不是所有的事情都应该用 AJAX 来完成。有时,简单的旧 HTML 更适合工作。我猜你的按钮有a
标签?你为什么不做这样的事情
<a href="generate_excel.php" target="_blank">Export to Excel</a>
in your HTML? Note the target="_blank"
part. It's there to make sure your page is not reloaded.
在你的 HTML 中?注意target="_blank"
部分。它可以确保您的页面不会重新加载。
For input
you can use construct
因为input
你可以使用构造
<form action="generate_excel.php" target="_blank"><input type="button">...whatever</form>
回答by Debajit Mukhopadhyay
I don't think you can download anything by ajax call. Instead of you can generate and save the excel in server (temporary) and show the download link to the user.
我认为你不能通过 ajax 调用下载任何东西。而不是您可以在服务器(临时)中生成并保存excel并向用户显示下载链接。
回答by shasi kanth
You can try this way:
你可以试试这个方法:
- Send a Jquery AJAX POST request with the data that is to be used to generate excel report, and store that data in a session variable. Return an arbitrary string like 'success' as the response.
- If the output of the above AJAX call is 'success', then do a GET request to another URL in your application, that reads the data from session (stored in the first step, else throw an error), prepares an excel file out of that data, and forces the download of that excel file to the browser.
- 发送带有用于生成 Excel 报告的数据的 Jquery AJAX POST 请求,并将该数据存储在会话变量中。返回一个像“成功”这样的任意字符串作为响应。
- 如果上述 AJAX 调用的输出为“成功”,则对应用程序中的另一个 URL 执行 GET 请求,该请求从会话中读取数据(存储在第一步中,否则抛出错误),准备一个 excel 文件该数据,并强制将该 Excel 文件下载到浏览器。