我想编写一个 javascript 函数,将 HTML 内容作为给定函数的 URL 的字符串返回。我在 Stackoverflow 上找到了类似的答案。
我正在尝试使用 this answer解决我的问题。
但是,似乎 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>
最佳答案
你需要在 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 内容作为字符串返回。函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10642289/