[英]How to display a PDF in iframe with ajax after calling a servlet
I have a problem when I want to display a PDF in an iframe (using the attribute src).The PDF is never downloaded from the browser. 我想在iframe中显示PDF时遇到问题(使用属性src)。永远不会从浏览器下载PDF。 I need to use an ajax call to display a message in a popup in some cases.
在某些情况下,我需要使用ajax调用在弹出窗口中显示消息。 The code of the servlet that generate the PDF works because currently we use this directly in the src attribute of the iframe.
生成PDF的Servlet的代码有效,因为当前我们直接在iframe的src属性中使用它。
<iframe src="myServlet" />
But when I use the servlet with a ajax call, and I want to add the content of the PDF in the iframe, it doesn't work. 但是,当我将servlet与ajax调用一起使用时,又想在iframe中添加PDF的内容时,它将无法正常工作。 I don't know why.
我不知道为什么 This is an example of the js :
这是js的示例:
$.ajax(
{
url: "myServlet",
...
complete: function(data) {
var blob = new Blob([data], { type: 'application/pdf' });
var downloadUrl = URL.createObjectURL(blob);
$('#myframe').attr("src", downloadUrl);
}
}
);
I try with chrome and I have the error: jquery-2.1.3.js?ts=13012017:3 GET data:application/pdf;base64,blob: http://localhost:8180/d21d82b6-8254-4a38-907e-129b3ac037fa net::ERR_INVALID_URL 我尝试使用chrome,但出现错误:jquery-2.1.3.js?ts = 13012017:3 GET data:application / pdf; base64,blob: http:// localhost:8180 / d21d82b6-8254-4a38-907e- 129b3ac037fa net :: ERR_INVALID_URL
I can see that I have the data as a binary file: %PDF-1.4 % 3 0 obj <>stream x {PU ^A e ( ...................... ................... startxref 38448 %%EOF 我可以看到我的数据是二进制文件:%PDF-1.4% 3 0 obj <> streamx {PU ^A e (........ .................................... startxref 38448 %% EOF
Sorry but I don't have the code here (at home), but I think that the explanations are fairly clear. 抱歉,这里(家里)没有代码,但我认为解释很清楚。 I don't know why the PDF cannot be downloaded if I use ajax with iframe and attribut src.
我不知道为什么如果我将ijax与iframe和attribut src一起使用,为什么无法下载PDF。 Do you have an idea?
你有想法吗?
Thanks. 谢谢。 Fred
弗雷德
This do the trick for me. 这对我有用。
$.ajax(
{
url: "myServlet",
...
complete: function(data) {
$('#myframe').attr('src','data:application/pdf;base64,'+data);
}
}
);
Also, you should encode the ajax ans this way base64_encode($data)
. 另外,您应该以这种方式对ajax ans进行编码
base64_encode($data)
。
I hope you find this helpful. 我希望你觉得这有帮助。
In Javascript, to encode the ajax answer you should do it this way: 在Javascript中,要对ajax答案进行编码,您应该这样做:
var enc = btoa(data)
If you have problems, you should try this: 如果遇到问题,请尝试以下操作:
var enc = btoa(unescape(encodeURIComponent(data)))
Then 然后
$('#myframe').attr('src','data:application/pdf;base64,'+ enc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.