Javascript: how to enter an external html file? (in the same domain)

I am trying to insert an external html file into the current DOM using javascript. This is in the same domain, so single-origin policies are not a problem.

var body = document.getElementsByTagName('body')[0];
var script= document.createElement('p');
script.innerHTML = 'http://samedomain.com/my.html';
body.appendChild(script);

any ideas?

+3
source share
2 answers

If it is in the same domain, you can use XmlHttpRequest (which works differently in different browsers) or just add an invisible iframe to the document with an attribute srcthat has the value of the page you want to load, and then get the parent element of the iframe node of the document body object innerHTMLproperty (non-standard, but widely supported).

, - , , .

iframe; :

  (function(){

    // our callback: do this when the remote document loads.
    function callback() {
      var b = frames['my_hidden_frame'].document.body;
      var response = (b.parentElement||b.parentNode).innerHTML;
      // do whatever you need to do here
      alert(response);
    }


    // create an iframe
    var e = document.createElement('iframe');

    // your ajax content
    e.src = '/some/local/path';

    // give the frame an id
    e.id = 'my_hidden_frame';

    // make the iframe invisible, but don't just display:none, 
    // because some browser (forgot which, old safari?) screws it up
    e.style.height='0px';
    e.style.width='0px';
    e.style.position='absolute';
    e.style.left='-100px';

    e.onload=callback;

    // put it in the body, it will load.
    document.body.appendChild(e);

  }());
+2

JSOP , Gist.

: . http://gist.github.com/5710.js

ajax, html, document.write .

, html-, html- .

0

Source: https://habr.com/ru/post/1765914/


All Articles