Get html content from url javascript

I want to write a javascript function that returns HTML content as string given URL to the function. I found a similar answer on Stackoverflow.

I am trying to use this answer to solve my problem.

However, it seems as though document.write() isn't writing anything. When I load the page, I get a a blank screen.




  
  


asked May 17, 2012 at 19:29

4

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

Get html content from url javascript

answered May 17, 2012 at 19:35

SatyaSatya

8,4585 gold badges33 silver badges52 bronze badges

6

The only one i have found for Cross-site, is this function:





answered Aug 26, 2013 at 15:19

otaxige_aolotaxige_aol

3431 gold badge4 silver badges6 bronze badges

2

after you get the response just do call this function to append data to your body element

function createDiv(responsetext)
{
    var _body = document.getElementsByTagName('body')[0];
    var _div = document.createElement('div');
    _div.innerHTML = responsetext;
    _body.appendChild(_div);
}

@satya code modified as below

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            createDiv(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();    
}

Get html content from url javascript

answered May 17, 2012 at 19:39

Get html content from url javascript

Pranay RanaPranay Rana

172k35 gold badges236 silver badges261 bronze badges

0

Here's a version of the accepted answer that 1) returns a value from the function (bugfix), and 2) doesn't break when using "use strict";

I use this code to pre-load a .txt file into my