JavaScript: how to load dynamic contents (HTML String, JSON) to iframe

转载 2012年08月15日 07:44:03

The story

Although people are suggesting the replacement of <iframe> by <div> due to the poor usability of <iframe>,  there are still some cases that <iframe> is the only way to go.

Consider such case : you want to show a preview screen before the user hit “submit” button on a page with form (the data input page). When the preview button is hit, an ajax request is sent to the server asking a validation of the user input. Then the server either generates the preview page HTML code (if the input is valid) or error message (if the input is not valid), in JSON format. The client receives the JSON response. If the JSON is an error message, then the client alerts user the error, otherwise, presents the preview screen (the HTML codes in JSON).

All of these seem very straight forward, until the time that you are presenting the preview page HTML codes. As the preview page HTML is a full set of HTML code, including the <html>, <head> and <body>tags, and more importantly it includes a new set of CSS styles and JavaScript codes. If you present these codes inside a <div> tag, the new CSS styles and JavaScript codes will definitely interferer the CSS styles and JavaScript codes of the data input page, making the both preview screen and the data input page extremely awful.

In such case, the proper way is to present the preview screen as an independent section from the data input page. This is where <iframe> should be used instead of <div>. Everything in <iframe> is independent from its parent document, so the <iframe> can have its own <doctype>, <html>,<head>, <body>, and CSS styles and JavaScript.

The problem

However, according to the specification of <iframe>, the content of <iframe> is specified by the “src” attribute which accepts values in URL format, like “”. It cannot load dynamic HTML codes. Moreover, as <iframe> is treated like an independent section from the current page, JavaScript frameworks such as jQuery has limited ability to modify its contents: you can only select and modify the contents inside the <body> of the <iframe> contents, you can do nothing outside the <body>, not to mention the jQuery ready() function doesn’t even work properly for <iframe>.

The solution

However, after some studies on the relationship between <iframe> and its associated document contents and combined the discussion on the web, we successfully inject HTML codes into an <iframe>. Here is how we do that:

1 <html>
2     <head>
3     </head>
4 <body>
5     <h1>Test iframe</h1>
6     <iframe id="test_iframe" src="about:blank" width=400 height=400></iframe>
8     <button onClick="javascript:injectHTML();">Inject HTML</button>
9 </body>
11 <script language="javascript">
12 function injectHTML(){
14     //step 1: get the DOM object of the iframe.
15     var iframe = document.getElementById('test_iframe');
17     var html_string = '<html><head></head><body><p>iframe content injection</p></body></html>';
19     /* if jQuery is available, you may use the get(0) function to obtain the DOM object like this:
20     var iframe = $('iframe#target_iframe_id').get(0);
21     */
23     //step 2: obtain the document associated with the iframe tag
24     //most of the browser supports .document. Some supports (such as the NetScape series) .contentDocumet, while some (e.g. IE5/6) supports .contentWindow.document
25     //we try to read whatever that exists.
26     var iframedoc = iframe.document;
27         if (iframe.contentDocument)
28             iframedoc = iframe.contentDocument;
29         else if (iframe.contentWindow)
30             iframedoc = iframe.contentWindow.document;
32      if (iframedoc){
33          // Put the content in the iframe
35          iframedoc.writeln(html_string);
36          iframedoc.close();
37      else {
38         //just in case of browsers that don't support the above 3 properties.
39         //fortunately we don't come across such case so far.
40         alert('Cannot inject dynamic contents into iframe.');
41      }
43 }
45 </script>
46 </html>

We have tested this code with Firefox 3.5 / 4 / 5, IE 6,7,8,9 and Chrome and fortunately all of them supports the dynamic HTML loading with this method.

c#将json转换为dynamic对象 (推荐)

来自: DynamicJsonConverter类...
  • ArvinStudy
  • ArvinStudy
  • 2013年03月07日 16:38
  • 2200


public string ZZJG_InsertOrUpdateData(string json)         {             ZZJG_Service zs_=new ZZJG...
  • leonardo_dream
  • leonardo_dream
  • 2016年04月09日 10:43
  • 480


iframe在复合文档中经常用到,利用jquery操作iframe可以大幅提高效率。   DOM方法: 父窗口操作IFRAME:window.frames["iframeSon"].docume...
  • vip_linux
  • vip_linux
  • 2013年08月19日 16:01
  • 1270


DynamicJsonConverter类如下:using System; using System.Collections; using System.Collections.Generic; us...
  • xinma
  • xinma
  • 2015年12月02日 16:07
  • 1915

ie下面用iframe实现图片上传,返回json格式时提示打开或保存。 基于iFrame的异步文件上传 IN: 原创作品| 技术 2四月...
  • cdnight
  • cdnight
  • 2014年02月25日 10:35
  • 6118


w3c标准的浏览器(如火狐、chrome等)是有一个对象JSON(注意是大写)专门用来处理json的。这个对象有两个函数: JSON.parse(text) //用于解析json;
  • ymjring
  • ymjring
  • 2012年06月05日 12:49
  • 25318

使用 JavaScript 创建和分析 JSON 消息

使用 JavaScript 创建和分析 JSON 消息将 JSON 用作数据交换格式时的两个常见任务是,将本机内存中的表示转换为其 JSON 文本表示,反之亦然。遗憾的是,在撰写文本时,JavaScr...
  • stonezhuzisgu
  • stonezhuzisgu
  • 2007年09月05日 15:14
  • 5973


function CheckVersion(obj, sec) {             jbxxsec = sec;             $("#txt_XMBH").val(
  • wangqiuchen_Study
  • wangqiuchen_Study
  • 2014年08月26日 17:08
  • 2898


JSON字符串: var str1 = ‘{ “name”: “cxh”, “sex”: “man” }’; //注意有单引号 JSON对象: var str2 = { “name”: “cx...
  • Akeron
  • Akeron
  • 2017年02月22日 11:56
  • 210


BIRT使用ScriptDataSet从POJO中获得数据(一) 2011-08-19 09:49 在前面说明过使用Script数据源来获得web service数据源的做...
  • shanliangliuxing
  • shanliangliuxing
  • 2011年09月01日 10:21
  • 1814
您举报文章:JavaScript: how to load dynamic contents (HTML String, JSON) to iframe