Load page content to variable

前端 未结 4 2256
余生分开走
余生分开走 2020-12-05 07:17

Good day.

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

How can i load a page content t

4条回答
  •  囚心锁ツ
    2020-12-05 07:55

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

    
    

    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'...

提交回复
热议问题