gpt4 book ai didi

php - jQuery 使用 AJAX 显示从 PHP 文件获取的 PDF 数据

转载 作者:行者123 更新时间:2023-12-01 04:01:08 25 4
gpt4 key购买 nike

我正在尝试使用 AJAX 查询 PHP 文件并向用户显示 PDF 文件。 PHP 文件的响应是存储在我的服务器上的 PDF 文件的原始数据。下面是我用来尝试完成此任务的代码,但它不起作用。我的浏览器不断收到错误请求错误。有谁知道这样做的正确方法?

我的最终目标是我不希望用户能够看到我存储 PDF 文件的服务器路径。我只希望可以使用 AJAX/PHP 脚本访问 PDF 文件。我知道这不是最安全的方法,但我只是想让外行人远离我的 PDF 文件。

jQuery:

$.ajax({
type: "POST",
url: 'process.php',
data: {"name" : "value"},
success: function (data) {
var json = $.parseJSON(data);
if(json.hasOwnProperty('success')){
window.location(json.success);
// json.success should contain the pdf binary data
// i just cant figure out how display the pdf in the browser
}
}
});

PHP:

<?php   
$fileName = $_POST['name'];
if(isset($fileName)){
$file = './path-to-forms/'.$fileName.'.pdf';
$pdfData = file_get_contents($file);
$data = array("success" => $pdfData, "name" => $fileName);
echo json_encode($data);
}
?>

最佳答案

Does anyone know the right way of doing this?

进行一些更改即可正确下载文件:

  • 更新 PHP 代码以使用 base-64 编码发送文件内容(即使用 base64_encode() ):

    $data = array("success" => base64_encode($pdfData));
  • 当 AJAX 响应完成时,创建一个 anchor (链接)并使用 .click() 模拟单击​​它。启动 PDF 下载。我在 api.jquery.com 上找不到任何 jQuery 方法 window.location() ……如果你找到了,请告诉我。也许您正在考虑更新(只读)属性 window.location

    var json = $.parseJSON(data);
    if(json.hasOwnProperty('success')){
    var a = document.createElement("a");
    a.href = 'data:application/pdf;base64,'+json.success;
    a.download = "filePDF"; //update for filename
    document.body.appendChild(a);
    a.click();
    // remove `a` following `Save As` dialog,
    // `window` regains `focus`
    window.onfocus = function () {
    document.body.removeChild(a)
    }
    }

    归功于 guest271314 的改编代码 this answer以及 answer below that 中 Alexandre 代码中的一些代码.

请参阅 this phpfiddle 中的演示.

关于php - jQuery 使用 AJAX 显示从 PHP 文件获取的 PDF 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com