테스트 환경에서 크로스 도메인 해결하기 CORS(Cross-Origin Resource Sharing)
json의 경우 jsonp로 우회해서 쓰지만 XML로 결과값이 떨어지는 경우는 아래처럼 해결했다.
사실 내가 개발 경력이 길지는 않지만 제일 짜증나는게 크로스도메인
임시 방편이기는 하지만 테스트할때 잠깐 씀
JS 파일이나 자바스크립트 매서드 선언 ( 야후의 개발자 콘솔을 프록시처럼 이용하여 사용)
/**
* 웹 프록시 사용
* @param theURL
* @param type
* @param callback
* @returns
* https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5 추울처
*/
function getFile(theURL, type, callback)
{
jQuery.ajax = (function(_ajax)
{
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url)
{
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o)
{
var url = o.url;
if (o.dataType == 'xml')
query = 'select * from xml where url="{URL}"'; // XML
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) )
{
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace('{URL}', url + (o.data ? (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data) : '')),
format: 'xml'
};
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success)
{
return function(data)
{
if (_success) {
_success.call(this, {
responseText: (data.results[0] || '').replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
return $.ajax({
url: theURL,
type: 'GET',
dataType: type,
success: function(res) {
callback ? callback(res) : undefined;
}
})
};
사용방법은 공공데이터 포털 API 활용 샘플 소스 참고 AJAX 호출하듯이 쓰면됨
http://jsbin.com/kibisoyazi/edit?html,output