[英]How to return a file using an AJAX request
我使用以下ajax調用將一些數據發送到PHP頁面,該頁面生成一個excel文件。 如果我使用已分配給數組的虛假數據單獨運行PHP頁面,它將下載文件,但是如果我嘗試通過ajax按鈕運行php頁面,則不會下載任何內容。 我不確定是什么問題,但是由於php嘗試發回文件,我收到500 Internal Server Error
。 見下文:
請求標頭:
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
響應標題:
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
我正在使用的ajax是:
$.ajax({
url: "XLS.php",
type: "post",
data: {xl: xl},
}); //closes ajax call
我經歷了大約7種不同的contenttype:
選項以查看其中之一是否contenttype:
,但沒有一個contenttype:
。
我如何找回這個文件?
如果您希望使用ajax請求下載文件,則有兩種可能。
通過將用戶重定向到下載頁面來偽造它,然后
作為斯基達頓指出注釋而不是使用POST參數使用GET參數
window.location = 'XLS.php?x1='+x1;
或使用執行類似Ajax的文件下載體驗的jquery.fileDownload庫
使用ajax(xrh請求)是不可能的。
AJAX請求永遠不會將文件下載到用戶PC。
解決方案是make和invisible iframe,並向其發布表單,然后瀏覽器將尊重您的標頭,指示下載。
抱歉,目前沒有適合您的示例,但希望以正確的方向解決您的工作,從而避免浪費更多的時間進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.