Skip to content Skip to sidebar Skip to footer

Load Html Contents Of A Given Url And Place Exactly There (like Document.write()) In Javascript

I want to write a JavaScript code that load HTML contents of a given URL and place the loaded HTML code exactly where the script is placed. (maybe this looks like functionality of

Solution 1:

Getting the current script tag is possible, but here's another approach (keep in mind it replaces the entire element with the id tag):

In the body tag:

<scriptid='test'>docWrite('test', '/echo/html')</script>

Javascript declaring a new function:

functiondocWrite(id, url) {
    var xmlhttp = newXMLHttpRequest(),
        _id = id;

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 
             && xmlhttp.status == 200) {
            var el = document.getElementById(_id),
                textnode = el.firstChild,
                div = document.createElement('div');

            div.id = _id;
            div.appendChild(textnode);

            el.parentNode.insertBefore(div, el.nextSibling);
            el.parentNode.removeChild(el);

            console.log(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", url, false );
    xmlhttp.send();
}

http://jsfiddle.net/dpgk1Lx2/

Here, all I'm doing is copying the contents of the id-related tag (there is no responseText to display). In your usage, you would do this instead:

functiondocWrite(id, url) {       
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 
             && xmlhttp.status == 200) {
            var el = document.getElementById(_id)
                div = document.createElement('div');

            div.id = _id;
            div.appendChild(xmlhttp.responseText);

            el.parentNode.insertBefore(div, el.nextSibling);
            el.parentNode.removeChild(el);
        }
    }

    xmlhttp.open("GET", url, false );
    xmlhttp.send();
}

Solution 2:

I know you are looking for a jQuery-less version... but I'm going to post this first... just to indicate how simple it is (and it works around browser differences in making AJAX calls, handling callbacks etc. for you).

<divid="someID"></div><script>$('#someID').load('someurl.html');</script>

Post a Comment for "Load Html Contents Of A Given Url And Place Exactly There (like Document.write()) In Javascript"