재우니의 블로그

 

크로스 브라우저에서 xmlhttprequest 방식으로 호출하여 반환하는 값

 

This script demonstrates how to access resources that sits on a different domain. Example: siteA.com gets resource from siteB.com

다른 도메인간 자원을 접근하는 방법의 코드이다. 즉, siteA.com 에서 siteB.com 사이트를 호출하여 데이터를 가져올 경우의 스크립트 이다. 

 

http://data.iampro.net/16469

 


// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    // true : 비동기; false : 동기
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

 

 

// Helper method to parse the title tag from the response.
function getTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

 

 

// Make the actual CORS request.
function getXmlHttp(url) {
  // All HTML5 Rocks properties support CORS.
  //var url = 'http://updates.html5rocks.com';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);

    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}


</script>