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.

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

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败