给定URL,以字符串形式返回HTML内容。Javascript功能

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


慕虎7371278
浏览 752回答 3
3回答

白衣非少年

当readystate == 4时,您需要返回function httpGet(theUrl){&nbsp; &nbsp; if (window.XMLHttpRequest)&nbsp; &nbsp; {// code for IE7+, Firefox, Chrome, Opera, Safari&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=new XMLHttpRequest();&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {// code for IE6, IE5&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");&nbsp; &nbsp; }&nbsp; &nbsp; xmlhttp.onreadystatechange=function()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (xmlhttp.readyState==4 && xmlhttp.status==200)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return xmlhttp.responseText;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; xmlhttp.open("GET", theUrl, false );&nbsp; &nbsp; xmlhttp.send();&nbsp; &nbsp;&nbsp;}

猛跑小猪

得到响应后,只需调用此函数即可将数据追加到您的body元素中function createDiv(responsetext){&nbsp; &nbsp; var _body = document.getElementsByTagName('body')[0];&nbsp; &nbsp; var _div = document.createElement('div');&nbsp; &nbsp; _div.innerHTML = responsetext;&nbsp; &nbsp; _body.appendChild(_div);}@satya代码修改如下function httpGet(theUrl){&nbsp; &nbsp; if (window.XMLHttpRequest)&nbsp; &nbsp; {// code for IE7+, Firefox, Chrome, Opera, Safari&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=new XMLHttpRequest();&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {// code for IE6, IE5&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");&nbsp; &nbsp; }&nbsp; &nbsp; xmlhttp.onreadystatechange=function()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (xmlhttp.readyState==4 && xmlhttp.status==200)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; createDiv(xmlhttp.responseText);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; xmlhttp.open("GET", theUrl, false);&nbsp; &nbsp; xmlhttp.send();&nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP