doujianmin6527 2015-03-13 19:04
浏览 495

如何使用AJAX请求返回文件

I use the following ajax call to send some data over to a PHP page, which generates an excel file. If I run the PHP page by itself with fake data already ascribed to an array, it downloads the file, but if I try to run the php page through the ajax button, nothing downloads. I'm not sure what the issue is, but I'm getting a 500 Internal Server Error as the php tries to send back the file. See below:

Request Headers:

POST /XLS.php HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Content-Length: 15
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Origin: http://127.0.0.1
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Referer: http://127.0.0.1/multiLine.php
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fr-FR;q=0.6,fr;q=0.4
Cookie: PHPSESSID=rd44cluc503datf36616b9e5b5; popupPartNumber=null

Response Headers:

HTTP/1.0 500 Internal Server Error
Date: Fri, 13 Mar 2015 18:21:55 GMT
Server: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.5.15
X-Powered-By: PHP/5.5.15
Content-disposition: attachment; filename="multiLine report 03.13.15 - .xlsx"
Content-Transfer-Encoding: binary
Cache-Control: must-revalidate
Pragma: public
Content-Length: 0
Connection: close
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

the ajax I'm using is:

$.ajax({
  url: "XLS.php", 
  type: "post",
  data: {xl: xl},
  }); //closes ajax call

and I've gone through about 7 different contenttype: options to see if one of those made the difference, but none of them did.

How do I get this file back?

  • 写回答

2条回答

  • dtgvl48608 2015-03-13 19:19
    关注

    If you're look to download a file using an ajax request you have two possibilities.

    Fake it by redirecting the user to the download page and

    As skidadon pointedin comment instead of using POST parameter use GET parameter

     window.location = 'XLS.php?x1='+x1;
    

    Or use the jquery.fileDownload library who perform an Ajax-like file download experience

    https://github.com/johnculviner/jquery.fileDownload

    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求