使用ajax Post请求更新iframe内容

时间:2011-08-10 09:54:12

标签: javascript ajax jquery iframe

我正在制作Rich文本编辑器。我有一个textarea和一个iframe。我想更新一个iframe内容点击某个按钮,其中ajax post请求传递给它textareas值。 这是我的HTML代码:

<textarea name="myTextarea" id="text" cols="100" rows="10"></textarea><br>
<br>
<input type="button" value="B" onclick="formatText (myTextarea,'b');" />
<input type="button" value="I" onclick="formatText (myTextarea,'i');" />
<input type="button" value="U" onclick="formatText (myTextarea,'u');" />
<input type="button" value="P" onclick="formatText (myTextarea,'p');" />
<input type="button" value="strike" onclick="formatText (myTextarea,'strike');"/>
<input type="button" value="h1" onclick="formatText (myTextarea,'h1');" />
<input type="button" value="h2" onclick="formatText (myTextarea,'h2');" />
<input type="button" value="h3" onclick="formatText (myTextarea,'h3');" />
<input type="button" value="h4" onclick="formatText (myTextarea,'h4');" />
<input type="button" value="h5" onclick="formatText (myTextarea,'h5');" />
<input type="button" value="h6" onclick="formatText (myTextarea,'h6');" />
<input type="button" value="center" onclick="alignText (myTextarea,'center');" />
<input type="button" value="left" onclick="alignText (myTextarea,'left');" />
<input type="button" value="right" onclick="alignText (myTextarea,'right');" />
<input type="button" value="justify" onclick="alignText (myTextarea,'justify');" />
<input type="button" value="preview" onclick="view(document.getElementById('text').value)">
<br><br><br>
<iframe id="upload_target" name="upload_target" src="#" style="width:1000px;height:1000px;border:2px;opacity:0;filter:alpha(opacity=0);"></iframe>

这是js view function:

function view(str)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  terms = "text="+str;
xmlhttp.onreadystatechange=function()
  {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById('upload_target').innerHTML="";
            jQuery.noConflict();
            (function($) {
            $('#upload_target').append(xmlhttp.responseText);
            })(jQuery);
        }
  }
  xmlhttp.open("POST","print1.php",true);
  xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(terms);
document.getElementById('upload_target').style.opacity=1;
}

我无法将我的textarea放入表单并将其定位到提交事件上的iframe,因为上面的代码只是我整个代码的一部分,而且它已经在表单中了。 w3c标准不允许使用嵌套表单 谢谢你的回复。

2 个答案:

答案 0 :(得分:4)

问题在于请求iframes内容的方法。正确的方法是:

document.getElementById("upload_target").contentWindow.document.body.innerHTML=x‌​mlhttp.responseText;

所有主流浏览器都支持它。

答案 1 :(得分:1)

为什么你不能简单地获取iframe并在ajax请求完成后用你的get参数更改url?如果您的iframe仅适用于GET。您也可以通过创建虚拟表单在iframe上触发POST请求并从javascript提交更多答案here