以字符串形式返回 HTML 内容,给定 URL.Javascript 函数

Return HTML content as a string, given URL. Javascript Function

本文关键字:给定 URL Javascript 函数 内容 HTML 字符串 返回      更新时间:2023-09-26

我想编写一个javascript函数,该函数将HTML内容作为给定URL的字符串返回给函数。我在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>

您需要在 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();    
}

我为跨站点找到的唯一一个是这个函数:

<script type="text/javascript">
var your_url = 'http://www.example.com';
</script>
<script type="text/javascript" src="jquery.min.js" ></script>
<script type="text/javascript">
// jquery.xdomainajax.js  ------ from padolsey
jQuery.ajax = (function(_ajax){
    var protocol = location.protocol,
        hostname = location.hostname,
        exRegex = RegExp(protocol + '//' + hostname),
        YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
        query = 'select * from html where url="{URL}" and xpath="*"';
    function isExternal(url) {
        return !exRegex.test(url) && /:'/'//.test(url);
    }
    return function(o) {
        var url = o.url;
        if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
            // Manipulate options so that JSONP-x request is made to YQL
            o.url = YQL;
            o.dataType = 'json';
            o.data = {
                q: query.replace(
                    '{URL}',
                    url + (o.data ?
                        (/'?/.test(url) ? '&' : '?') + jQuery.param(o.data)
                    : '')
                ),
                format: 'xml'
            };
            // Since it's a JSONP request
            // complete === success
            if (!o.success && o.complete) {
                o.success = o.complete;
                delete o.complete;
            }
            o.success = (function(_success){
                return function(data) {
                    if (_success) {
                        // Fake XHR callback.
                        _success.call(this, {
                            responseText: data.results[0]
                                // YQL screws with <script>s
                                // Get rid of them
                                .replace(/<script[^>]+?'/>|<script(.|'s)*?'/script>/gi, '')
                        }, 'success');
                    }
                };
            })(o.success);
        }
        return _ajax.apply(this, arguments);
    };
})(jQuery.ajax);

$.ajax({
    url: your_url,
    type: 'GET',
    success: function(res) {
        var text = res.responseText;
        // then you can manipulate your text as you wish
        alert(text);
    }
});
</script>

收到响应后,只需调用此函数即可将数据附加到您的 body 元素

function createDiv(responsetext)
{
    var _body = document.getElementsByTagName('body')[0];
    var _div = document.createElement('div');
    _div.innerHTML = responsetext;
    _body.appendChild(_div);
}

@satya代码修改如下

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)
        {
            createDiv(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();    
}

在一般情况下你不能这样做

。因为浏览器使用同源策略来限制站点 A 上运行的代码对站点 B 的访问。当您尝试(使用 XMLHttpRequestfetch 等(时,您会收到一条错误消息,内容如下:

请求的资源上不存在"访问控制允许源"标头

更多内容请参阅此问题的答案和上面的 SOP 链接。但基本上:这不是要阻止人们看到站点 B 的内容,而是要无法从可能存储当前用户的身份验证信息的上下文(浏览器(执行此操作,如果您可以从该用户的浏览器读取站点 B 的内容,则会泄露他们的私人信息。

极少数网站可能会使用跨源资源共享标头(上述Access-Control-Allow-Origin和其他标头(来提供其内容,以允许任何网站读取其内容,但这非常不寻常。

如果要检索绝大多数站点的内容,则必须使用在非浏览器上下文中运行的代码来执行此操作(例如,在某处服务器上运行的代码(。多年来,有许多网站允许您使用 URL 查询它们并返回其服务器查询的该 URL 的内容(因此不受 SOP 的约束,因为当前用户对其他站点的基于浏览器的身份验证信息未使用(,但它们往往会涌现然后再次消失,因为没有真正好的收入模型来支持带宽要求。毕竟,当您可以以便宜(甚至免费(的价格运行自己的服务器并自己动手时,为什么要为此向其他人付费。

这是一个接受答案的版本,1( 从函数(错误修复(returns一个值,2( 使用时不会中断"use strict";

当用户加载页面时,我使用此代码将.txt文件预加载到我的<textarea>中。

function httpGet(theUrl)
{
    let xmlhttp;
    
    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();
    
    return xmlhttp.response;
}

在某些网站中,XMLHttpRequest可能会向您发送类似 <script src="#"></srcipt> 的内容。在这种情况下,请尝试使用类似于以下脚本的 HTML 文档:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

现在你可以用JS从HTML中获取一些文本,比如getElementbyId

但这可能不适用于某些具有跨域阻止的网站。