2014-12-07 1 views
0

자바 스크립트를 사용하여 웹 사이트에서 페이지를 가져오고 싶습니다. 내가 같은 URL이 있습니다에서자바 스크립트에서 URL로 일부 페이지를 얻는 방법

http://not-my-site.com/random 

'임의'나는이 웹 사이트의 다른 (임의) 페이지로 리디렉션됩니다.
우편 배달부 내가 원하는 것처럼 다하십시오 :) 그것은 전체 페이지 (HTML)를 얻습니다. 하지만 어떻게 자바 스크립트에서 동일한 작업을 수행 할 수 있습니까?
본 가이드 http://www.html5rocks.com/en/tutorials/cors/에 따라 CORS alredy를 시도했지만 성공하지 못했습니다. 튜토리얼에서

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. 

코드 : 나는 여전히 오류 얻을

var xhr = new XMLHttpRequest(); 
xhr.open('GET', 'http://not-my-site.com/random', true); 
xhr.send(); 
+0

이 오류를 제공하는 코드를 게시 해주십시오. (MCVE 인 경우 추가 보너스) – fxm

+0

cors를 시도해 볼만한 것은 없습니다. 원격 사이트 중 하나를 구현하고 그것을 작동하지 않거나, 그리고 서버 쪽 프록시 또는 나중에 경우 YQL 같은 서비스를 사용 제외하고 할 수있는 아무것도 ... – dandavis

+0

마지막으로, 나는 모든 근원을 사용했습니다. 잘 작동합니다 ... http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-jquery-ajax – Alendorff

답변

0

이가 보인다

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을 시도 (동일한 오류가 발생했습니다) 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

관련 문제