Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return HTML content as a string, given URL. Javascript Function

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.

<html> <head> </head> <body>     <script type="text/JavaScript">   function httpGet(theUrl)   {     var xmlHttp = null;      xmlHttp = new XMLHttpRequest();     xmlHttp.open( "GET", theUrl, false );     xmlHttp.send( null );     return xmlHttp.responseText;   }   document.write(httpGet("https://stackoverflow.com/"));   </script> </body> </html> 
like image 689
Jason Kim Avatar asked May 17 '12 19:05

Jason Kim


People also ask

How do I get HTML using JavaScript?

Get HTML elements by TagName: In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").


1 Answers

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();     } 
like image 70
Satya Avatar answered Sep 16 '22 16:09

Satya