【问题标题】:Get HTML code using JavaScript with a URL使用带有 URL 的 JavaScript 获取 HTML 代码
【发布时间】:2011-09-16 13:20:59
【问题描述】:

我正在尝试通过使用带有 URL 的 XMLHttpRequest 来获取 HTML 的源代码。我该怎么做?

我是编程新手,我不太确定没有 jQuery 怎么办。

【问题讨论】:

  • 你可能想看看同源策略的问题...只要搜索 SO,你会发现大量的信息。
  • 但是还有其他方法可以解决这个问题吗?喜欢不使用 xmlhttprequest?只用 javascript?
  • 没有。 xmlhttprequest 和 iframes 是唯一的方法,两者都受同源策略的限制。如果你想解决这个问题,远程服务器需要合作(通过作为 jsonp 服务,或者在它服务的数据上放置一个特殊的标头)

标签: javascript html ajax url xmlhttprequest


【解决方案1】:

我在使用 fetch api 时遇到了问题,并且它似乎总是返回承诺,即使它返回文本 "return await response.text();" 并且要使用文本处理该承诺,它需要使用 .then 在异步方法中处理。

     <script>
                // Getting the HTML
                async function FetchHtml() 
                {
                    let response = await fetch('https://address.com');
                    return await response.text(); // Returns it as Promise
                }
        
        
                // Usaing the HTML
                async function Do()
                {
                   let html = await FetchHtml().then(text => {return text}); // Get html from the promise
                    alert(html);
                }
        
        
                // Exe
                Do();
</script>

【讨论】:

    【解决方案2】:

    首先,您必须知道您将永远无法获得与您的 javascript 页面不在同一个域中的页面的源代码。 (见http://en.wikipedia.org/wiki/Same_origin_policy)。

    在 PHP 中,您可以这样做:

    file_get_contents($theUrl);
    

    在javascript中,有三种方式:

    首先,通过 XMLHttpRequest : http://jsfiddle.net/635YY/1/

    var url="../635YY",xmlhttp;//Remember, same domain
    if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
    if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open('GET',url,true);
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
    };
    xmlhttp.send(null);
    

    其次,通过 iFrames: http://jsfiddle.net/XYjuX/1/

    var url="../XYjuX";//Remember, same domain
    var iframe=document.createElement("iframe");
    iframe.onload=function()
    {
        alert(iframe.contentWindow.document.body.innerHTML);
    }
    iframe.src=url;
    iframe.style.display="none";
    document.body.appendChild(iframe);
    

    第三,jQuery: [http://jsfiddle.net/edggD/2/

    $.get('../edggD',function(data)//Remember, same domain
    {
        alert(data);
    });
    

    ]4

    【讨论】:

      【解决方案3】:

      编辑:还不行...

      将此添加到您的 JS:

      var src = fetch('https://page.com')
      

      它将page.com的来源保存到变量'src'

      【讨论】:

        【解决方案4】:

        对于外部(跨站点)解决方案,您可以使用:Get contents of a link tag with JavaScript - not CSS

        它使用$.ajax()函数,所以它包含jquery。

        【讨论】:

          【解决方案5】:

          这里有一个关于如何使用 Ajax 的教程:https://www.w3schools.com/xml/ajax_intro.asp

          这是取自该教程的示例代码:

          <html>
          
          <head>
              <script type="text/javascript">
                  function loadXMLDoc()
                  {
                      var xmlhttp;
                      if (window.XMLHttpRequest)
                      {
                        // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
                        xmlhttp = new XMLHttpRequest();
                      }
                      else
                      {
                          // Code for Internet Explorer 6 and Internet Explorer 5
                          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                      }
                      xmlhttp.onreadystatechange=function()
                      {
                          if (xmlhttp.readyState==4 && xmlhttp.status==200)
                          {
                              document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                          }
                      }
                      xmlhttp.open("GET", "ajax_info.txt", true);
                      xmlhttp.send();
                  }
              </script>
          </head>
          
          <body>
              <div id="myDiv"><h2>Let AJAX change this text</h2></div>
              <button type="button" onclick="loadXMLDoc()">Change Content</button>
          </body>
          
          </html>
          

          【讨论】:

            【解决方案6】:

            使用 jQuery:

            $.ajax({ url: 'your-url', success: function(data) { alert(data); } });
            

            此数据是您的 HTML。

            没有 jQuery(只有 JavaScript):

            function makeHttpObject() {
              try {return new XMLHttpRequest();}
              catch (error) {}
              try {return new ActiveXObject("Msxml2.XMLHTTP");}
              catch (error) {}
              try {return new ActiveXObject("Microsoft.XMLHTTP");}
              catch (error) {}
            
              throw new Error("Could not create HTTP request object.");
            }
            
            var request = makeHttpObject();
            request.open("GET", "your_url", true);
            request.send(null);
            request.onreadystatechange = function() {
              if (request.readyState == 4)
                alert(request.responseText);
            };
            

            【讨论】:

            • @Senad Meskin 感谢您的回答,但是否可以使用 jQuery 来完成?我想知道是否有其他方法可以做到这一点。
            • 你的 url 是否指向另一台服务器,如果是这样,那就是安全问题。
            • @Senad Meskin 可以说是 google.com 还是 youtube.com?有可能吗?
            • 不,这是不可能的,你唯一能做的就是调用你的 url,在服务器端代码调用 www.google.com 并写入 google.com 的响应内容
            • 如果源没有设置“Access-Control-Allow-Origin”标头,这会起作用吗?
            【解决方案7】:

            您可以使用fetch 来做到这一点:

            fetch('some_url')
                .then(function (response) {
                    switch (response.status) {
                        // status "OK"
                        case 200:
                            return response.text();
                        // status "Not Found"
                        case 404:
                            throw response;
                    }
                })
                .then(function (template) {
                    console.log(template);
                })
                .catch(function (response) {
                    // "Not Found"
                    console.log(response.statusText);
                });
            

            带箭头功能的异步版本:

            (async () => {
                var response = await fetch('some_url');
                switch (response.status) {
                    // status "OK"
                    case 200:
                        var template = await response.text();
            
                        console.log(template);
                        break;
                    // status "Not Found"
                    case 404:
                        console.log('Not Found');
                        break;
                }
            })();
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-05-09
              • 1970-01-01
              • 2014-07-29
              • 1970-01-01
              • 2013-04-13
              • 1970-01-01
              • 1970-01-01
              • 2012-01-06
              相关资源
              最近更新 更多