javascript - 给定 URL,将 HTML 内容作为字符串返回。函数

标签 javascript html

我想编写一个 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/

相关文章:

python - 使用 BeautifulSoup4 和 Python 3 解析 html 表

html - 图片叠加...仅在真实图片的区域而不是图片的背景

javascript - 条件注释 - 包含基于 IE 版本的 javascript

javascript - 视口(viewport)中幻灯片上的滑动 slider 事件类和仅一张幻灯片上的当前类

javascript - 如何设置 Twitter 关注按钮,在关注后启用另一个按钮

Javascript:2 个用户输入值的平均值

Javascript 在 HTML 上创建按钮并触发 onclick 函数

javascript - angular-annotate-asset-pipeline 在 Grails 2 项目中根本不起作用

javascript - Chrome 中的轻微 CSS 对齐问题

javascript - "onchange"事件在 IE 中延迟? (适用于 Firefox)