使用带有网址的javascript获取HTML代码

sim*_*ied 16 html javascript ajax url xmlhttprequest

我试图通过使用带有url的xmlhttprequest来获取html的源代码.有没有人可以帮我这个?我是编程新手,我不太清楚如果没有jQuery我怎么能这样做.提前致谢.

Sen*_*kin 24

使用jQuery:

$.ajax({ url: 'your-url', success: function(data) { alert(data); } });
Run Code Online (Sandbox Code Playgroud)

这些数据是您的HTML.

没有jQuery(只是JS):

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);
};
Run Code Online (Sandbox Code Playgroud)

  • 如果源未设置“Access-Control-Allow-Origin”标头,这会起作用吗? (2认同)

Tân*_*Tân 8

您可以使用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);
    });
Run Code Online (Sandbox Code Playgroud)

与箭头函数版本异步:

(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;
    }
})();
Run Code Online (Sandbox Code Playgroud)


Guy*_*Guy 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 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)
    {
    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>
Run Code Online (Sandbox Code Playgroud)