2014-12-07 33 views
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(); 
+0

請問您可以發佈代碼給你這個錯誤嗎? (如果它是MCVE,額外的獎勵) – fxm 2014-12-07 00:47:58

+0

沒有什麼可以嘗試一下cors;無論是遠程站點實現它,它的工作原理或它沒有,除了在後面的情況下使用服務器端代理或服務,如YQL,沒有什麼可以做... – dandavis 2014-12-07 01:00:32

+0

最後,我用了Whatever Origin。工作正常... http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-jquery-ajax – Alendorff 2014-12-07 02:01:07

回答

0

這似乎是CORS未在服務器上正確配置的問題。下面的PHP代碼應該允許來自任何域的任何請求。 (如果你不使用PHP,應該很容易將下面的代碼轉換成任何其他語言,線索是寫入HTTP頭)。

請記住在之前輸入此代碼輸出任何HTML。

$origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:$_SERVER['HTTP_HOST']; 
header('Access-Control-Allow-Origin: '.$origin);   
header('Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT'); 
header('Access-Control-Allow-Credentials: true'); 
header('Access-Control-Allow-Headers: Authorization, X-Requested-With'); 
header('P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"'); 
header('Access-Control-Max-Age: 1'); 

接受來自所有域的請求是不安全的。對於更好的(但稍微複雜一點的)解決方案,請參閱:CORS That Works In IE, Firefox, Chrome And Safari

相關問題