給定URL,以字符串形式返回HTML內容Javascript功能
您需要在readystate == 4時返回,例如
function httpGet(theUrl){ if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); } xmlhttp.onreadystatechange=function() {if (xmlhttp.readyState==4 && xmlhttp.status==200){ return xmlhttp.responseText;} } xmlhttp.open('GET', theUrl, false ); xmlhttp.send(); }解決方法
我想編寫一個JavaScript函數,該函數以給定URL的字符串形式返回HTML內容。我在Stackoverflow上找到了類似的答案。
但是,似乎document.write()什么也沒寫。加載頁面時,出現空白屏幕。
<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>
