0

I want to view source code of current page using Javascript, so I use this snippet code:

function getSourceCode() {
var url="http://localhost:8080/java/",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)
    xmlhttp = new XMLHttpRequest();
if("ActiveXObject" in window)
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4){
        var a = xmlhttp.responseText;
        alert(a);
        document.getElementById("demo").innerHTML = a;
    }
};
xmlhttp.send(null);
}

And in HTML file, I declared a line

to print out the variable stored all source code like it alert to screen. But it always alert to my screen without print to variable "a" in the html screen.

This is my HTMl code:

<!DOCTYPE html>
<html>
<head>
    <title>Vo Tinh Thuong</title>
    <script src="code.js"></script>
</head>
<body> 
<input id="clickMe" type="button" value="clickme" onclick="getSourceCode();" />
<p id="demo"></p>
</body>
</html>

I just want to print out the variable to html webpage, not alert it like that.

Sae
  • 41
  • 8

2 Answers2

0

you are sending an asynchronous request, hence it is unable to print the response. You have to keep the code in a callback and pass the response to callback from that. You can find the clean explanation in this answer (or) check this

function callBack(a){
 document.getElementById("demo").innerHTML = a;
}

call this callBack(a)

Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51
0

I just solved my problem. If I want to put the "a" variable content "responseText" of source code of current page, I should put it into textarea instead p tag.

Sae
  • 41
  • 8