简体   繁体   English

使用 JavaScript 获取特定页面的源代码

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

The code below displays the source code of the current page:下面的代码显示了当前页面的源代码:

Website as example: http://jsfiddle.net/635YY/1/网站为例: 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);

How to display the source code of another page (other than the current page)?如何显示另一个页面(当前页面除外)的源代码?

url="/about";

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

  alert( this.responseXML.documentElement.innerHTML );

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

Unfortunately you will not be able to do this with pages on another website unless the CORS policy on the website allows it, or you will get an error like不幸的是,除非网站上的 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