0

我需要将数据发送到 php 文件并下载它。

当我直接调用它时,我的脚本工作正常,但是当我使用 AJAX 发送数据时,它根本不会下载。

我的问题是:如何将数据发送到 php 文件并自动下载文件,但当然要保持在同一页面上?

直接调用时工作的部分代码......

PHP 文件

header('Content-Description: File Transfer'); 
header("Content-type: application/ms-word");
header("Content-Disposition: attachment;Filename=ponuda.doc");

$productsArr = json_decode($_POST['object']);
$html = "<tr>";
foreach($productsArr as $product)
{
    //something
}
....
echo $html;

AJAX 调用:

$.ajax({
          type: "POST",
          url: "test_download.php",
          data: { object:productsJSON },
          cache: false
        });
4

2 回答 2

0

我执行以下操作:

  1. 在 head 部分中包含exchange.js javascript 文件
  2. 在页面加载时初始化交换器对象:theBuffer = new exchanger('dwnld');
  3. 创建一个 javascript 函数,当您想要启动文件下载时将调用该函数:

     function downloadFile(){
          // you can add parameters to the function as needed to pass in dynamic data sent to the back end download handler
          data = "http://your_backend_file_download_handler.php?param1=val1&param2=val2&etc=whatever";  // send whatever data you need to the php program via query string parameters
          theBuffer.sendData(data);  // initiate the file download
     }
    

    注意:处理请求的 php 后端文件下载程序可以对您发送的参数做任何需要做的事情,以便组合/检索正确的数据/文件以供下载。经过多次修补后,这种组合一直对我 有用

  4. 在您的正文部分中包含这一点 html。我通常把它放在结束体标签之前:

     <iframe name="dwnld" id="dwnld" style="width:0;height:0;border:0">
     </iframe>
    
     Note:  the id value assigned to the iframe is the same value given in step 2 when initializing.
    

结果是用户永远不会离开当前页面来下载任何数量的文件,因为实际下载是在单独的页面(也称为 iframe)中处理的。多年来,我在所有项目中都毫无问题地使用了它。

于 2013-07-18T18:46:54.633 回答
0

我认为您不能通过 ajax 将标头发送到浏览器,但是您可以使用它,很棒。

http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

$.fileDownload('file.mp3')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });
于 2013-07-18T19:28:31.297 回答