【问题标题】:How to load iframe using POST with header如何使用带有标头的 POST 加载 iframe
【发布时间】:2019-08-17 18:49:44
【问题描述】:
我需要将网页加载到 iframe 中。网页服务器由 Open ID Connect 保护,需要一个不记名令牌进行授权。为了呈现页面,还需要通过服务器发送数据。响应的内容也有一些 JavaScript。 iframe src 只允许有一个使用 GET 方法的 URL,它不能提供我们想要的。
总之,我需要:
- 使用 POST 将网页加载到 iframe 中
- 在 Authorsation 标头中包含令牌。
- 在 iframe 中加载页面后加载 javascript
【问题讨论】:
标签:
javascript
ajax
post
iframe
header
【解决方案1】:
我采用的方法是使用 AJAX post 来加载页面 html 和 JavaScript 的内容。获得内容后,我们将内容写入 iframe contentwindows。
我研究了一些替代方法:
- 使用表单发布。这不允许将令牌包含到授权标头中
- 使用 jQuery html 方法。这不会触发 iframe 加载 html。所以返回页面中的 JavaScript 不起作用。
工作示例:https://jsfiddle.net/duongthaiha/wmLsrfo0/52/
这里是一些代码sn-p:
function loadHTMLToIframe(data) {
alert(data);
var iframe = document.getElementById('targetIframe');
var iframedoc = iframe.document;
if (iframe.contentDocument)
iframedoc = iframe.contentDocument;
else if (iframe.contentWindow)
iframedoc = iframe.contentWindow.document;
if (iframedoc){
// write content to the iframe
iframedoc.open();
iframedoc.writeln(data);
iframedoc.close();
//page loaded at this point
} else {
alert('Fail to get the content windows');
}
}
参考:http://thinkofdev.com/javascript-how-to-load-dynamic-contents-html-string-json-to-iframe/