问题描述
您需要在readystate == 4时返回,例如
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();
}
解决方法
我想编写一个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>