【问题标题】:Display pdf in browser for ajax response在浏览器中显示 pdf 以进行 ajax 响应
【发布时间】:2016-01-28 04:55:01
【问题描述】:

我想在浏览器中显示 pdf ajax 响应。问题是我无法直接打开 url,因为 pdf 是动态创建的,我该如何显示它。

$.ajax({
                    url: url,
                    type: "POST",
                    data: JSON.stringify(data),
                    processData: false,
                    contentType: "application/json; charset=UTF-8",
                    complete: function (response) {
                        console.log(response);
                        window.open("pdf.php","_blank");

                    }
                });

PDF 响应是

%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode /Length 1265>>

PHP 代码

 header('Cache-Control: public');
 header('Content-type: application/pdf');
 header('Content-Disposition: attachment; filename="new.pdf"');  
 header('Content-Length: ' . strlen($data));
 echo $data;

应感谢任何帮助。

【问题讨论】:

  • 刚打开新窗口开始...把数据发布到新窗口。
  • 您遇到了什么错误?如果直接把pdf.php放到浏览器的地址栏会怎样?如果它有效,那么 JS 也应该有效。

标签: javascript php jquery ajax pdf


【解决方案1】:

把它放在你的 pdf.php 中

header("Content-type: application/pdf");

【讨论】:

  • 您的问题出在 pdf.php 文件中。添加该文件的相关代码。
【解决方案2】:

我遇到了这个问题,我会给你解决方案......我希望它能解决你的问题。

当您致电您的服务时,您应该要求dataType: 'binary' 回复。然后,使用saveAs(FileSaver.js) 触发下载。

但是,$.ajax 不允许您开箱即用地下载二进制内容,它会尝试从 UTF-8 解码您的二进制文件并破坏它。要么使用jQuery插件来解决这个问题jquery.binarytransport.js

示例:

$.ajax({
    type: "POST",
    url: $("form#data").attr("action"),
    data: formData,
    dataType: 'binary',     //--> using jquery.binarytransport.js
    success: function (response) {
        // Default response type is blob
        saveAs(response, "test.pdf"); //--> using FileSaver.js
    }
});

好看! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    相关资源
    最近更新 更多