dongzaobei0942 2018-04-16 12:00
浏览 40
已采纳

当Ajax调用调用时,PHP触发下载不起作用

I built a small PHP script which creates an Excel spreadsheet and forces its download, by defining the corresponding header. When I call this script directly by its URL (or even through JS with window.location.replace), everything works fine. Now, when I call the same script via an Ajax call (both synchronously and asynchronously) nothing happens.

Can somebody explain this behavior?

Regards Sebastian

  • 写回答

1条回答 默认 最新

  • dongyuluan7494 2018-04-16 13:39
    关注

    AJAX requests are processed in the background, so the download headers will be ignored and only passed to your callback.

    If you want to force download the file without redirecting him to the page you can

    • inject an iframe to the page and pass the download url as src-parameter
    • link to the download url with an a-tag and add the HTML5 download-attribute to it
    • put the result of your ajax-request base64-encoded in an injected a-tag as src parameter and pass a download-parameter.

    Example for downloading the url https://stackoverflow.com/ as "stackoverflow.html": <a href="https://stackoverflow.com/" download="stackoverflow.html">Click me!</a>

    Example for downloading the text "test" as "file.txt": <a href="data:text/plain;base64,dGVzdA==" download="file.txt">Click me</a> (where dGVzdA== is "test" base64-encoded)

    After injecting both a-tags you can use e.g. jQuery to simulate an user clicking on them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型