使用 JavaScript 和 URL 获取 HTML 代码

发布于 2024-11-15 13:30:53 字数 179 浏览 1 评论 0原文

我试图通过使用 XMLHttpRequest 和 URL 来获取 HTML 的源代码。我怎样才能做到这一点?

我是编程新手,我不太确定如果没有 jQuery 如何才能做到这一点。

I am trying to get the source code of HTML by using an XMLHttpRequest with a URL. How can I do that?

I am new to programming and I am not too sure how can I do it without jQuery.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

凶凌 2024-11-22 13:30:53

使用 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);
};

Use jQuery:

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

This data is your HTML.

Without jQuery (just 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);
};
如何视而不见 2024-11-22 13:30:53

您可以使用 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;
    }
})();

You can use fetch to do that:

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

Asynchronous with arrow function version:

(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;
    }
})();
画骨成沙 2024-11-22 13:30:53

这里有一个关于如何使用 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>

There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp

This is an example code taken from that tutorial:

<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>
柳絮泡泡 2024-11-22 13:30:53

我在 fetch api 方面遇到了问题,它似乎总是返回承诺,即使它返回文本 "return wait 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>

I had problems with the fetch api and it seams that it always returns promise even when it returns text "return await response.text();" and to handle that promise with the text, it needs to be handled in async method by using .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>
甜心小果奶 2024-11-22 13:30:53

对于外部(跨站点)解决方案,您可以使用:使用 JavaScript 获取链接标记的内容 - 而不是 CSS

它使用 $.ajax() 函数,因此它包括jquery。

For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS

It uses $.ajax() function, so it includes jquery.

首先,您必须知道,您将永远无法获取与您的 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 :< /strong> http://jsfiddle.net/edggD/2/

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

First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).

In PHP, this is how you do it:

file_get_contents($theUrl);

In javascript, there is three ways :

Firstly, by 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);

Secondly, by 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);

Thirdly, by jQuery : http://jsfiddle.net/edggD/2/

$.get('../edggD',function(data)//Remember, same domain
{
    alert(data);
});
骄兵必败 2024-11-22 13:30:53

编辑:还没有工作...

将其添加到您的 JS:

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

它将 page.com 的源保存到变量“src”

Edit: doesnt work yet...

Add this to your JS:

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

It saves the source of page.com to variable 'src'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文