0
我想使用javascript從網站獲取頁面。 我有喜歡的網址:如何在javascript中通過url獲取頁面
http://not-my-site.com/random
從「隨機」我將被重定向到的網址另一個(隨機)頁面。
郵差做我喜歡的一切:)它是整個頁面(html)。但我怎麼能做到這一點從JavaScript?
我試過CORS alredy按照這個指南http://www.html5rocks.com/en/tutorials/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();
請問您可以發佈代碼給你這個錯誤嗎? (如果它是MCVE,額外的獎勵) – fxm 2014-12-07 00:47:58
沒有什麼可以嘗試一下cors;無論是遠程站點實現它,它的工作原理或它沒有,除了在後面的情況下使用服務器端代理或服務,如YQL,沒有什麼可以做... – dandavis 2014-12-07 01:00:32
最後,我用了Whatever Origin。工作正常... http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-jquery-ajax – Alendorff 2014-12-07 02:01:07