我想使用 javascript 从网站获取页面。我有这样的网址:
http://not-my-site.com/random
从“随机”我将被重定向到网站上的另一个(随机)页面。
邮递员做我想做的一切:) 它得到整个页面(html)。但是我怎样才能从 javascript 做同样的事情呢?我已经按照本指南http://www.html5rocks.com/en/tutorials/cors/
尝试了 CORS ,但没有成功。我仍然只是得到一个错误:
XMLHttpRequest cannot load http://not-my-site.com/random.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
教程中的代码:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://not-my-site.com/random');
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var responseText = xhr.responseText;
console.log(responseText);
// process the response.
};
xhr.onerror = function() {
console.log('There was an error!');
};
xhr.send();
而且我也尝试过这样的常见xhr(得到了同样的错误):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://not-my-site.com/random', true);
xhr.send();