簡體   English   中英

使用 JavaScript 獲取特定頁面的源代碼

[英]Get source code for a specific page using JavaScript

下面的代碼顯示了當前頁面的源代碼:

網站為例: 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);

如何顯示另一個頁面(當前頁面除外)的源代碼?

url="/about";

var xhr = new XMLHttpRequest();
xhr.onload = function() {

  alert( this.responseXML.documentElement.innerHTML );

}
xhr.open( 'GET', url );
xhr.responseType = 'document';
xhr.send();

不幸的是,除非網站上的 CORS 政策允許,否則您將無法對其他網站上的頁面執行此操作,否則您將收到類似的錯誤

Access to XMLHttpRequest at 'https://test.com/' from origin 'http://jsfiddle.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM