下载一个文件,一个Ajax调用 [英] Download a file with an ajax call

查看:112
本文介绍了下载一个文件,一个Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHPExcel读取Excel模板,填充数据,并要求用户下载该文件。

I am using PHPExcel to read an excel template, populate the data, and ask the user to download the file.

generate_excel.php

generate_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');

当我从浏览器中打开generate_excel.php直接,结果文件被下载。 但是,如果我做的generate_excel.php Ajax调用,我没有得到的下载提示。使用Chrome的开发人员工具,我可以从网络选项卡Ajax调用成功完成和一堆随机字符看到的是出现在响应数据。我假设是Excel对象。

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.

有谁知道我怎么能Excel中使用AJAX功能实现下载?我不想刷新页面。当用户点击导出按钮,应该有到PHP文件Ajax调用,并提示用户下载用户。

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.

谢谢!

推荐答案

找到一种方法来做到这一点,虽然我不知道这是一种理想的方法。

Found a way to do this, although I'm not sure if this is an ideal approach.

我添加了一个隐藏的iframe页面。当Ajax调用返回时,它返回创建的数据的URL。我用JavaScript来的iframe重定向到URL自动触发下载操作。

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.

这篇关于下载一个文件,一个Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆