javascript xhr加载iframe作为回应

时间:2015-09-02 21:40:00

标签: javascript ajax iframe xmlhttprequest

有没有人知道如何使这个XHR请求响应将.php文件加载到iframe中而不是直接加载?

var xhr= new XMLHttpRequest();
    xhr.open('GET', 'http://derrick.dk/ogmobi/facebook/contentLockerFacebook.php', true);
    xhr.onreadystatechange= function() {
        if (this.readyState!==4) return;
        if (this.status!==200) return;
        document.getElementsByTagName('body')[0].innerHTML = document.getElementsByTagName('body')[0].innerHTML + this.responseText;    
};
xhr.send();

1 个答案:

答案 0 :(得分:5)

替换它:

document.getElementsByTagName('body')[0].innerHTML = document.getElementsByTagName('body')[0].innerHTML + this.responseText;

用这个:

var iframe = document.createElement('iframe');
iframe.srcdoc = this.responseText;
iframe.src = "data:text/html;charset=utf-8," + escape(this.responseText);
document.body.appendChild(iframe);

或者,如果您只想在iFrame中显示页面而不发出XHR请求。只需将其用作代码:

var iframe = document.createElement('iframe');
iframe.src = 'http://derrick.dk/ogmobi/facebook/contentLockerFacebook.php';
document.body.appendChild(iframe);