以给定URL的形式返回HTML内容。 Javascript函数 [英] Return HTML content as a string, given URL. Javascript Function

查看:59
本文介绍了以给定URL的形式返回HTML内容。 Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个javascript函数,它返回HTML内容作为给定函数的URL的字符串。我在Stackoverflow上找到了类似的答案。



我正在尝试使用此答案解决我的问题。
$ b 然而,它似乎好像 document.write() isn'不要写任何东西。当我加载页面时,我得到一个空白屏幕。



 < html> 
< head>
< / head>
< body>
< script type =text / JavaScript>
函数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例如

$ p $ 函数httpGet(theUrl)
{
if(window.XMLHttpRequest)
{/ / code for IE7 +,Firefox,Chrome,Opera,Safari
xmlhttp = new XMLHttpRequest();
}
else
{//代码为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();
}


I want to write a javascript function that returns HTML content as string given URL to the function. I found a similar answer on Stackoverflow.

I am trying to use this answer to solve my problem.

However, it seems as though document.write() isn't writing anything. When I load the page, I get a a blank screen.

<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>

解决方案

you need to return when the readystate==4 e.g.

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();    
}

这篇关于以给定URL的形式返回HTML内容。 Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆