2014-12-07 36 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

相关问题