Copy html content from iframe into div ( ajax )?

2019-04-07 15:02发布

Lets assume I have my browser load an Iframe with <iframe src="test.html">

Can I, using ajax, load the content of test.html into a div in the main html page?

This idea is my solution for that fact that I'm actually trying to overcome the limitation with making ajax submits to remote hosts. The plan is to generate the dynamic page with 0 sized iframe which makes report request to remote host. Then, after the page (& iframe content) loads I will copy the iframe content into a div using JS.

Tips are appreciated,

Thank you, Maxim.

5条回答
女痞
2楼-- · 2019-04-07 15:16

Can I, using ajax, load the content of test.html into a div in the main html page?

Yes (since your example has a relative URI and is on the same host) …

This idea is my solution for that fact that I'm actually trying to overcome the limitation with making ajax submits to remote hosts.

… and no. You still can't read data from remote hosts.

查看更多
时光不老,我们不散
3楼-- · 2019-04-07 15:17

... you may, however, design an AJAX request to local host and retrieve information from the remote server (as described here).

查看更多
小情绪 Triste *
4楼-- · 2019-04-07 15:21

No, you can't.

When you load a page from a different domain into the iframe, it becomes unreachable. You can no longer access the contents of the iframe, as it comes from a different domain.

The only thing that I know of that you can reliably load from a different domain is a script, which JSONP uses.

查看更多
Lonely孤独者°
5楼-- · 2019-04-07 15:22

If you write a php/perl/etc. script to output the contents of a document from another domain, it'll give you access to the contents as the resulting page would be considered by javascript to belong to your domain. If you're not familiar with any server-side scripting languages, I'm sure you'd be able to find a script that'll do this for you by doing a simple google search.

Best of luck.

查看更多
别忘想泡老子
6楼-- · 2019-04-07 15:23

I'm sure someone will correct me if I'm wrong, but I believe that scripting across domain boundaries is restricted. Have you tried it? Here's a function that may help out.

function insertDivFromFrame(divname, framename) {
    var frame = document.getElementById(framename);
    var d = frame.contentWindow || frame.contentDocument;
    if (oDoc.document) {d = d.document;}
    document.getElementById('yourdiv').innerHTML = d.body.innerHTML;
}

I'm not sure this code works... see http://xkr.us/articles/dom/iframe-document/ for more help on this.

查看更多
登录 后发表回答