问题描述
我想做 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?
推荐答案
如果您查询的 URL 实际返回 PDF 数据,则无法通过 XMLHttpRequest 进行.
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
属性将其加载到当前文档内的 中
Load it in an <iframe>
inside the current document by changing iframe's src
attribute
通过window.open(new_pdf_url, XXX)在单独的窗口中打开它
请注意,您仍然需要指向临时文件位置的 URL 才能打开新窗口
Please note that you STILL need a URL to a temp file location to open a new window
这篇关于XMLHttpRequest 在浏览器中打开 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!