我试图通过使用带有 URL 的 XMLHttpRequest 来获取 HTML 的源代码。我怎样才能做到这一点?
我是编程新手,我不太确定如果没有 jQuery 如何才能做到这一点。
使用 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);
};
您可以使用 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;
}
})();
这里有一个关于如何使用 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>
我在 fetch api 方面遇到了问题,它似乎总是返回 Promise,即使它返回文本
"return await response.text();"
并且要使用文本处理该 Promise,需要使用 .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>
首先,您必须知道,您将永远无法获得与您的 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);
});
编辑:尚未工作...
将其添加到您的 JS 中:
var src = fetch('https://page.com')
它将 page.com 的源代码保存到变量“src”