download pdf from ajax post


download pdf from ajax post

我想通过jquery帖子下载一个pdf文件。我试过这个:

$('#downloadPdf').click(function() {
    var id = $('#fileId').val();
    $.ajax({
        type: "POST",
        url: "includes/download_pdf.php",
        data: 'file_id=' + id,
        complete: function(data) {
            $('#pdf_results').html(data.responseText);
        }
    });
});

代码 PHP:

<?php 
    $file_name = $_POST['file_id']; 
    // We'll be outputting a PDF header('Content-type: application/pdf'); 
    // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="'.$file_name.'.pdf"'); 
    // The PDF source is in original.pdf readfile('/var/www/vhosts/domain.nl/private/'.$file_name.'.pdf'); 
?>

当我使用此代码时,我会得到所有奇怪的迹象#pdf_results.我想将PDF保存到我的计算机上,但这不起作用。

有人知道如何解决这个问题吗?

提前感谢!

你不需要

为此使用 AJAX。尝试使用这样的东西:

$(function(){
    $('#downloadPdf').click(function(){
        var id = $('#fileId').val();
        window.open(location.protocol + '//' + location.hostname + '/includes/download_pdf.php?file_id=' + id);
        return false;
    });
});

干杯!

这里不需要 ajax。

尝试使用Rory McCrossan的解决方案:发布到服务器,接收PDF,通过jQuery交付给用户

要么使用插件,要么简单地链接到文件并确保你的服务器发送正确的标头(否则你可以用php读取文件并从那里输出:http://www.saschakimmel.com/2009/05/php-prompt-the-user-to-download-a-specific-file/)

在页面上有一个不可见的<iframe/>,并创建一个具有属性method="POST" action="includes/download_pdf.php" target="name_of_the_iframe" <form>,在其中添加一个<input type="hidden" name="file_id" value="the_value"/>,然后提交它。

以上所有操作都可以在 JavaScript 中完成,而无需将这种标记放入页面中,以保持整洁。这些都不是阿贾克斯。

你需要实现这个:我没有真正跟踪您的程序,但是您需要php中的内容处置行才能使其工作。

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
**header('Content-Disposition: attachment; filename="downloaded.pdf"');**
// The PDF source is in original.pdf
readfile('original.pdf');
?>

在此处查看手册

您也可以将文件移动到iframe上,但这是一种安全风险,因此是另一个主题。