Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Good day.

I never really got a good hand at JavaScript, therefore this unusual and simple question.

How can i load a page content to a JavaScript variable, with the least amount of code, no framework, and the less impact possible on performance?

Thanks.


EDIT

Sorry guys. I forgot to mention: Get the page content from the specified url to a JS var.


Following Brendan Suggestion

I had already seen Brendan alternative elsewhere and tried it, but it didn't work at the time, and it doesn't work now. Meanwhile Firebug and the Browsers tested (IE8 and FF) don't report any error. So whats wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is a modified version of an example you can find at w3schools.com.

<script type="text/javascript">
    function loadXMLDoc(theURL)
    {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari, SeaMonkey
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                alert(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", theURL, false);
        xmlhttp.send();
    }
</script>

So just make "example.html" be any sort of path (relative or absolute) to the page you want to load, and xmlhttp.responseText will be a string containing the response content. You can also use xmlhttp.responseXML if you want it to be stored as a traversable XML document. Anyway, just assign either of those to a variable of your choice, and you will have it!

Note that 'loadXMLDoc' does not return anything directly but defines one of its members ('onreadystatechange') to do that job, and to does it only in certain condition (readyState and status). Conclusion - do not assign the output of this function to any var. Rather do something like:

var xmlhttp=false;
loadXMLDoc('http://myhost/mycontent.htmlpart');
if(xmlhttp==false){ /* set timeout or alert() */ }
else { /* assign `xmlhttp.responseText` to some var */ }

Without that, all one can see is 'undefined'...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...