개요 : HTTP GET 방식 요청을 통해 서버로부터 받은 JavaScript 파일을 로드하고 실행합니다.
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
url 정보를 요청할 URL
success(data, textStatus, jqXHR) 요청이 성공하면 실행될 콜백 함수
이 함수의 가장 간단한 사용법은 아래와 같습니다.
$.ajax({
url: url,
dataType: "script",
success: success
});
스크립트가 실행되면 다른 변수에서 접근이 가능하고 jQuery 함수에서도 사용할 수 있습니다. 포함된 스크립트는 현재 페이지에 영향을 줄 수 있습니다.
Success Callback
이 콜백함수는 JavaScript 파일을 반환 받습니다. 스크립트가 이미 이 시점에서 실행되므로 이것은 일반적으로 유용하지 않습니다.
$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");
스크립트는 파일이름을 참고한 후 로드하고 실행됩니다.
$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
});
Handling Errors
jQuery 1.5 부터 .fail() 함수를 사용할 수 있게 되었습니다.
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
jQuery 1.5 이전 버젼에서는, .ajaxError() 콜백 이벤트에 $.getScript() 에러 처리 구문을 포함해서 사용해야 합니다.
$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
if (settings.dataType=='script') {
$(this).text( "Triggered ajaxError handler." );
}
});
Caching Responses
기본적으로 $.getScript() 의 cache 속성값은 false 입니다. 스크립트를 요청시에 URL에 timestamped 를 포함하여 브라우져가 항상 새로운 스크립트를 요청하도록 하십시오. cache 속성의 전역값을 새로 세팅하려면 $.ajaxSetup()에서 하셔야 합니다.
$.ajaxSetup({
cache: true
});
예 제
캐싱된 스크립트를 가져올 수 있도록 $.cachedScript() 함수에서 정의합니다.
jQuery.cachedScript = function(url, options) {
// allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
// Usage
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
console.log( textStatus );
});
음, 솔직히 말씀드려서 위 예제가 실행되면 어떻게 된다는 건지 정확하게 모르겠습니다. :-(
예 제
공식 jQuery 컬러 애니메이션 플러그인 파일을 로드하고 특정 컬러를 반영합니다.
<!DOCTYPE html>
<html>
<head>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
jquery.color.js 파일을 열어보세요. 무지 복잡하게 뭐라무라 되어 있네요. 그중에 colors = jQuery.Color.names 변수에 위 예제에 있는 blue와 pink 에 대한 16진수 값이 들어 있습니다. 그 js 파일을 열어서 관련 로직을 반영시키는 것입니다.