首页 > 解决方案 > 如何使用带有标头的 POST 加载 iframe

问题描述

我需要将网页加载到 iframe 中。网页服务器由 Open ID Connect 保护,需要一个不记名令牌进行授权。为了呈现页面,还需要通过服务器发送数据。响应的内容也有一些 JavaScript。iframe src 只允许有一个使用 GET 方法的 URL,它不能提供我们想要的。

总而言之,我需要:

标签: javascriptajaxpostiframeheader

解决方案


我采用的方法是使用 AJAX post 来加载页面 html 和 JavaScript 的内容。获得内容后,我们将内容写入 iframe contentwindows。我研究了一些替代方法: - 使用表单发布。这不允许将令牌包含到授权标头中 - 使用 jQuery html 方法。这不会触发 iframe 加载 html。所以返回页面中的 JavaScript 不起作用。

工作示例:https ://jsfiddle.net/duongthaiha/wmLsrfo0/52/

这是一些代码片段:

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/


推荐阅读