XMLHttpRequest 在浏览器中打开 PDF [英] XMLHttpRequest to open PDF in browser

查看:53
本文介绍了XMLHttpRequest 在浏览器中打开 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做 XMLHttpRequest,然后通过 POST 方法发送文件名,在浏览器中打开一个 PDF.

I want to do XMLHttpRequest and then open a PDF in the Browser by sending the filename by POST method.

   xmlhttp.open("POST","pdf.php",true); //CHANGE
   xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
   xmlhttp.send("file="+input);

这可能还是 XMLHttpRequest 仅适用于 HTML?

Is that possible or XMLHttpRequest is just for HTML?

推荐答案

  1. 如果您查询的 URL 实际返回 PDF 数据,则无法通过 XMLHttpRequest 进行.

  1. It is not possible to do via XMLHttpRequest if the URL you are querying actually returns the PDF data.

为什么?因为响应是包含原始 PDF 数据的 HTTP 响应.没有 JavaScript 功能可以用包含在该数据中的 PDF 的呈现替换当前文档的 DOM 内容,即使您确实可以通过 responseText` 属性(另见 http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute).

Why? Because the response is an HTTP response which contains raw PDF data. There is no JavaScript ability to replace the current document's DOM contents with a rendering of a PDF contained in that data, even though you DO have access to the data via responseText` attribute (also see http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute).

您可以做的是将 PDF 文件生成为可通过 Web 服务器中的 URL 访问的临时文件,然后让脚本发回用于访问该文件的 URL.

What you CAN do is to generate a PDF file into a temporary file accessible via a URL from your web server, and then have the script send back the URL for accessing that file.

当您的响应处理程序处理 URL 时,它可以:

When your response handler processes the URL, it can either:

  • 通过更改 window.location.href = new_pdf_url

通过更改 iframe 的 src 属性将其加载到当前文档内的