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>
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.
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").
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With