반응형

http://code.google.com/p/iscroll-js/
http://cubiq.org/iscroll
The overflow:scroll for mobile webkit. Project started because webkit for iPhone does not provide a native way to scroll content inside a fixed size (width/height) div. So basically it was impossible to have a fixed header/footer and a scrolling central area. Until now.

How to use

First of all we need to prevent the default behavior of standard touch events. This is easily done adding preventDefault() to the touchmove event. Then initialize the iScroll object on DOMContentLoaded or on window load. Here an example:

function loaded() {
	document.addEventListener('touchmove', function(e){ e.preventDefault(); });
	myScroll = new iScroll('scroller');
}
document.addEventListener('DOMContentLoaded', loaded);

iScroll takes two parameters. The first is mandatory and is the ID of the element you want to scroll. The second is optional and can be used to pass additional parameters (see below).

On the HTML/CSS side the scrolling area needs to be wrapped by an element which determines the scroller actual size. The following is a common tags configuration for an iScroll.

<div id="wrapper">
    <div id="scroller">
        <ul>
            <li>...</li>
        </ul>
    </div>
</div>

The #wrapper also needs some classes:

#wrapper {
    position:relative;
    z-index:1;
    width:/* your desired width, auto and 100% are fine */;
    height:/* element height */;
    overflow:/* hidden|auto|scroll */;
}

That’s it. Enjoy your scrolling. Have a look at the source code of the online example to get a better idea of how the iScroll works.

Syntax

The iScroll syntax is: iScroll(mixed element_id, object options).

element_id, can be both an object pointing to or a string with the ID name of the element to be scrolled. Example: iScroll(document.getElementsByTagName('div')[1]) or iScroll('scroller')

Accepted options are:

  • hScrollbar: set to false to never show the horizontal scrollbar. The default value true makes the iScroll smartly decide when the scrollbar is needed. Note that if device does not support translate3d hScrollbar is set to false by default.
  • vScrollbar: set to false to never show the vertical bar. The default value true makes the iScroll smartly decide when the scrollbar is needed. Note that if device does not support translate3d vScrollbar is set to false by default.
  • bounce: set to false to prevent the scroller to bounce outside of boundaries (Android behavior). Default true (iPhone behavior).
  • bounceLock:, if set to true the scroller stops bouncing if the content is smaller than the visible area. Default: false (as per native iphone scroll).
  • checkDOMChanges: set to false to prevent auto refresh on DOM changes. If you switch off this feature you have to call iScroll.refresh() function programmatically every time the DOM gets modified. If your code makes many subsequent DOM modifications it is suggested to set checkDOMChanges to false and to refresh the iScroll only once (ie: when all changes have been done). Default true.
  • fadeScrollbar: define wether the scrollbars should fade in/out. Default true on iPhone, false on Android. Set to false for better performance.
  • momentum: set to false to remove the deceleration effect on swipe. Default true on devices that support translate3d.
  • shrinkScrollbar: set to false to remove the shrinking scrollbars when content is dragged over the boundaries. Default true on iPhone, false on Android. It has no impact on performances.
  • desktopCompatibility: for debug purpose you can set this to true to have the script behave on desktop webkit (Safari and Chrome) as it were a touch enabled device.
  • snap: set to true to activate snap scroll.
  • scrollbarColor: changes the color of the scrollbar. It accepts any valid CSS color (default: 'rgba(0,0,0,0.5)'

Note: options must be sent as object not string. Eg:

myScroll = new iScroll(’scroller’, { checkDOMChanges: false, bounce: false, momentum: false });

Snap scroll

When calling iScroll with “snap” option the scrolling area is subdivided into pages and whenever you swipe the scroll position will always snap to the page. Have a look at the screencast to get an idea.

Probably the best way to use “snap” is by calling it without momentum and scrollbars:

new iScroll('scroller', { snap:true, momentum:false, hScrollbar:false, vScrollbar:false });

If you keep momentum, you get a free-scrolling that will always stop to prefixed positions.

To have a perfect snapping experience the scrolling area should be perfectly divisible by the container size. Eg: If the container width is 200px and you have 10 elements, the whole scroller should be 2000px wide. This is not mandatory as iScroll doesn’t break if the last page is smaller than the container.

Methods

  • refresh(): updates all iScroll variables. Useful when the content of the page doesn’t scroll and just “jumps back”. Call refresh() inside a zero setTimeout. Eg: setTimeout(function () { myScroll.refresh() }, 0).
  • scrollTo(x, y, timeout): scrolls to any x,y location inside the scrolling area.
  • scrollToElement(el, runtime): scrolls to any element inside the scrolling area. el must be a CSS3 selector. Eg: scrollToElement("#elementID", '400ms').
  • scrollToPage(pageX, pageY, runtime): if snap option is active, scrolls to any page. pageX and pageY can be an integer or prev/next. Two keywords that snap to previous or next page in the raw. The “carousel” example in the zip file is a good starting point on using the snap feature.
  • destroy(full): completely unloads the iScroll. If called with full set to true, the scroller is also removed from the DOM.

Best practices

DOM Changes – If scrolling doesn’t work after an ajax call and DOM change, try to initialize iScroll with checkDOMChanges: false and call refresh() function once the DOM modifications have been done. If this still doesn’t work try to put refresh() inside a 0ms setTimeout. Eg:

setTimeout(function () { myScroll.refresh(); }, 0);

Performance – CSS animations are heavy on the small device CPU. When too many elements are loaded into the scrolling area expect choppy animation. Try to reduce the number of tags inside the scrolling area to the minimum. Try to use just ULs for lists and Ps for paragraphs. Remember that you don’t actually need an anchor to create a button or send an action, so <li><a href="#" onclick="..." />text</a></li> is a waste of tags. You could remove the anchor and place the click event directly on the LI tag.

Try to avoid box-shadow and CSS gradients (especially on Android). I know they are cool and classy, but they don’t play well with CSS animations. Webkit on iPhone seems to handle shadows and gradients a bit better than its counterpart on Android, so you may selectively add/remove features based on the device.

Use a flat color for the #wrapper background, images in the scroller wrapper once again reduce performance.

Important: to preserve resources on devices that don’t support translate3d (namely: Android<2.0) iScroll disables momentum, scrollbars and bounce. You can however reactivate them using the respective options.

반응형
반응형

http://code.google.com/p/jquery-infinite-carousel/

download : http://code.google.com/p/jquery-infinite-carousel/downloads/list

Add an infinite carousel on your site, the easy way. See a Demo here

Features

  • Really easy way to insert a quality HTML carousel on your site
  • Loop infinitely over items when clicking next or previous button
  • Avoid animation flickering due to multi-clicks on next and previous buttons

Some HTML

<div id="viewport"> 
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<a id="previous">Previous</a>
<a id="next">Next</a>

<!--
ul/li structure can be replaced by any other html structure as div/div, div/span...
-->

Some CSS

/* Comments on styles purpose in the source code */ 
#viewport{
width
: 240px;
overflow
:hidden;
}
#viewport ul{
position
: relative;
padding
: 0;
}
#viewport li{
width
: 100px;
height
: 50px;
float: left;
list
-style: none;
}

Some JavaScript : the magic

$('#viewport').carousel('#previous', '#next');

Tips

If you need to activate auto-scrolling on your carousel, simply simulate a click :

//The auto-scrolling function 
function slide(){
$
('#simpleNext').click();
}
//Launch the scroll every 2 seconds
var intervalId = window.setInterval(slide, 2000);

//On user click deactivate auto-scrolling
$
('#previous, #simpleNext').click(
function(event){
if(event.originalEvent){
window
.clearInterval(intervalId);
}
}
);






반응형
반응형
A highly adaptable jQuery plugin for creating carousels and slideshows

download : http://code.google.com/p/carouslide/downloads/list

CarouSlide is an easy-to-implement, flexible yet powerful jQuery plugin that allows you to create a wide range of different carousel and slideshow implentations, from a small and semantic list of HTML content.

Some of its optional features include:

Three types of animation: fade, slide vertically and slide horizontally

  • Back/Next controls
  • Infinite horizontal scrolling
  • Timed/Automatic animations (including play/pause button)
  • Hover activation on navigation
  • Optional use of Easing plugin for animations
  • Adjustable animation timings
  • 9Kb (minified) file size

All you need to get going is:

$(".CarouSlide").CarouSlide();




반응형
반응형
http://docs.phonegap.com/phonegap_accelerometer_accelerometer.md.html#Accelerometer

http://docs.phonegap.com/index.html

Accelerometer

Captures device motion in the x, y, and z direction.

Methods

Arguments

Objects (Read-Only)

반응형
반응형

http://wowslider.com/ajax-jquery-slider-pulse-blinds-demo.html

WOW Slider - jQuery Carousel & Slider

WOW Slider is a jQuery Image Slider with stunning visual effects and fancy templates.

Features

  • # Awesome and unique transitions: Blinds, Fly, Squares, Explosion, Fade, Slices, Basic
  • # Stylish pre-made designs: Noir, Pulse, Crystal, Noble, Chrome, Block
  • # Lightweight (4-12Kb uncompressed)
  • # Prev/Next controls
  • # Bullet navigation
  • # Customizable speed, delay, size etc.
  • # Cross-browser compatibility
  • # Search engine friendly
  • # Clean and valid markup

More Info: http://wowslider.com/
Live Demos: http://wowslider.com/automatic-jquery-slider-noir-squares-demo.html
http://wowslider.com/ajax-jquery-slider-pulse-blinds-demo.html
http://wowslider.com/jquery-slider-crystal-basic-demo.html


Recent Demos


반응형
반응형

Step Carousel Viewer v1.9


Description: Step Carousel Viewer displays images or even rich HTML by side scrolling them left or right. Users can step to any specific panel on demand, or browse the gallery sequentially by stepping through x number of panels each time. A smooth sliding animation is used to transition between steps. And fear not in taming this script to go exactly where you want it to- two public methods, two custom event handlers, and three "status" variables are here for that purpose. Some highlights of this script:

  • Contents for the Step Carousel Viewer can be defined either directly inline on the page or via Ajax and extracted from an external file instead.

  • Ability to specify whether panels should wrap after reaching the two ends, or stop at the first/last panel.

  • Panel persistence supported, so the last viewed panel can be remembered and recalled within the same browser session.

  • Ability for Carousel to auto rotate as dictated by the new parameter: autostep: {enable:true, moveby:1, pause:3000} During this mode, Carousel pauses onMouseover, resumes onMouseout, and clicking Carousel halts auto rotation altogether.

  • Option to specify two navigational images that's automatically positioned to the left and right of the Carousel Viewer to move the panels back and forth.

  • Ability to auto generate pagination images based on the total number of panels within a Carousel and positioned anywhere on the page. v1.8 feature

  • The contents of a Carousel can be updated on demand after the page has loaded with new contents from an external file. v1.8 feature

Demo #1: Auto rotation enabled (every 3 seconds, 1 panel each time), left/right nav buttons enabled, pagination buttons enabled.

Demo #2: Wrap around enabled ("slide"), left/right nav buttons enabled, pagination buttons enabled, status variables enabled.

Current Panel: 1 Total Panels: 5

Back 1 Panel Forward 1 Panel
To 1st Panel Forward 2 Panels

Demo #3: Wrap around enabled ("pushpull"), variable content widths, moves 2 panels at a time, illustration of new content loaded on demand.

1
2
3
4
5

Back Forward
Currently showing panels: 3 to 5


반응형
반응형

Having fun with HTML5 — Local Storage and Session Storage


API

The full API spec­i­fi­ca­tion for the local­Stor­age and ses­sion­Stor­age objects can be found here. At the time of writ­ing, this is how the com­mon Stor­age inter­face look:

image

Demo

I’ve put together a quick demo here to illus­trate how to detect and use the local and ses­sion stor­age to get, set, remove and clear stored items (well, basi­cally, cov­ers each of the avail­able meth­ods on the Stor­age inter­face above).

The page itself is sim­ple and crude, just a cou­ple of <div> and most impor­tantly two tables which I use to show all the key value pairs stored in the local and ses­sion storage:

image

Intro­duc­ing the new place­holder attribute

You might have noticed that the two text boxes had place­holder text sim­i­lar to that famil­iar search box in Firefox:

text boxes with place holder text Firefox search box

This is done using HTML5’s place­holder attribute for the <input> tag:

1
2
<input id="keyText" placeholder="Enter key"/>
<input id="valueText" placeholder="Enter value"/>

Nice and easy, eh? ;-)

Set­ting an item

To add a new key value pair or update the value asso­ci­ated with an exist­ing key, you just have to call the setItem method on the intended stor­age object:

1
2
3
4
5
6
7
8
9
10
11
12
13
// adds a new key to both local and session storage
function setKey() {
var key = $("#keyText").val();
var value = $("#valueText").val();
if (Modernizr.localstorage) {
localStorage.setItem(key, value);
}
if (Modernizr.sessionstorage) {
sessionStorage.setItem(key, value);
}
showKeys();
}
Remov­ing an item

Ear­lier in the showStorageKeys(type, table) func­tion, I added a row to the rel­e­vant table for each key value pair in the stor­age includ­ing a but­ton with a han­dler for the onclick event. The han­dlers are cre­ated with the cor­rect stor­age type (“local” or “ses­sion”) and key for the cur­rent row baked in already so that they will call the removeItem(type, key) func­tion with the cor­rect parameters:

1
2
3
4
5
6
7
// removes an item with the specified key from the specified type of storage
function removeItem(type, key) {
// get the specified type of storage, i.e. local or session
var storage = window[type + 'Storage'];
storage.removeItem(key);
showKeys();
}
Clear­ing all items

Finally, the ’”Clear” but­tons under­neath the tables call the clear­LocalKeys() and clearS­es­sion­Keys() func­tion to remove all the key value pairs in the cor­re­spond­ing storage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function clearLocalKeys() {
clearKeys("local");
}
function clearSessionKeys() {
clearKeys("session");
}
// clear all the held keys in the specified type of storage
function clearKeys(type) {
// get the specified type of storage, i.e. local or session
var storage = window[type + 'Storage'];
// clear the keys
storage.clear();
showKeys();
}


반응형
반응형

JSONP를 사용한 도메인 간 통신, Part 1: JSONP와 jQuery의 결합으로 강력한 매시업 빠르게 만들기

http://www.ibm.com/developerworks/kr/library/wa-aj-jsonp1/

소개

Ajax(Asynchronous JavaScript and XML)는 흔히 Web 2.0 사이트라고 하는 새로운 세대의 웹 사이트를 선도하는 핵심 기술이다. Ajax를 사용하면 웹 애플리케이션의 표시 및 동작에 영향을 주지 않고 백그라운드에서 데이터를 검색할 수 있다. 데이터는 클라이언트 측 JavaScript에서 HTTP로 원격 서버에 연결하는 기능을 제공하는 API인 XMLHttpRequest 함수를 사용하여 검색된다. 또한 Ajax는 여러 소스의 컨텐츠를 단일 웹 애플리케이션에 통합하는 많은 매시업에서 기본 기술로 사용되고 있다.

하지만 이 방법을 사용할 경우에는 브라우저의 제한사항으로 인해 도메인 간 통신이 지원되지 않는다. 다른 도메인의 데이터를 요청하려고 하면 보안 오류가 발생한다. 물론 데이터가 있는 원격 서버를 제어하고 동일한 도메인에만 데이터를 요청한다면 이러한 보안 오류를 막을 수 있다. 하지만 웹 애플리케이션이 고유 서버에만 한정되어 있다면 무슨 의미가 있겠는가? 여러 써드파티 서버에 있는 데이터를 수집해야 하는 경우에는 어떻게 할 것인가?

동일 출처 정책 제한 이해

동일 출처 정책은 한 도메인에서 로드된 스크립트가 다른 도메인의 문서 특성을 가져오거나 조작하지 못하도록 한다. 즉, 요청된 URL의 도메인이 현재 웹 페이지의 도메인과 같아야 한다. 이는 기본적으로 브라우저가 다른 출처의 컨텐츠를 조작하는 것을 방지하기 위해 해당 컨텐츠를 분리한다는 것을 의미한다. 이 브라우저 정책은 아주 오래 전인 Netscape Navigator 2.0부터 사용되던 것이다.

비교적 간단하게 이 제한을 해결하려면, 웹 페이지에서 자신의 출처가 되는 웹 서버에 데이터를 요청하고 해당 웹 서버가 실제 써드파티 서버에 요청을 전달하는 프록시 서버 역할을 수행하면 된다. 많이 사용되고 있기는 하지만 이 기술은 확장성이 없다. 또 다른 방법으로는 프레임 요소를 사용하여 현재 웹 페이지 내에 새 영역을 만든 후 GET 요청을 사용하여 써드파티 컨텐츠를 가져오는 방법이 있다. 하지만 컨텐츠를 가져온 이후에 프레임의 컨텐츠가 동일 출처 정책 제한에 걸릴 수 있다.

이 제한을 해결할 수 있는 방법은 웹 페이지에 동적 스크립트 요소를 삽입하는 것이다. 이 스크립트 요소에는 다른 도메인의 서비스 URL을 가리키는 소스가 있기 때문에 스크립트 자체적으로 데이터를 가져올 수 있다. 이 스크립트는 로드되면서 실행된다. 이 방법은 동일 출처 정책에서 동적 스크립트 삽입이 허용되고 스크립트가 웹 페이지의 소스 도메인에서 로드된 스크립트로 간주되기 때문에 정상적으로 작동된다. 하지만 이 스크립트에서 다른 도메인의 문서를 로드하려는 시도는 실패하게 된다. 다행히 JSON(JavaScript Object Notation)을 함께 사용하면 이 기술을 향상시킬 수 있다.

JSON과 JSONP

JSON은 XML에 비해 브라우저와 서버 간의 정보 교환에 사용되는 경량 데이터 형식이다. JSON은 이름에서 알 수 있듯이 JavaScript 오브젝트의 문자열 표현이다. (이 사실을 간과하는 JavaScript 개발자들이 없기를 바란다.) 예를 들어, symbol과 price라는 두 속성을 가진 ticker 오브젝트가 있다고 가정해 보자. JavaScript에서는 다음과 같이 ticker 오브젝트를 정의할 수 있다.

var ticker = {symbol: 'IBM', price: 91.42};

다음은 동일한 정의를 JSON으로 표현한 것이다.

{symbol: 'IBM', price: 91.42}

JSON과 JSON을 데이터 교환 형식으로 사용할 수 있는 가능성에 대한 자세한 정보는 참고자료에서 볼 수 있다. Listing 1에서는 호출되었을 때 IBM 주가를 보여 주는 JavaScript 함수를 정의한다. (이 기사에서는 코드를 웹 페이지에 통합하는 방법에 대한 상세 설명을 제공하지 않는다.)


Listing 1. showPrice 함수 정의하기
function showPrice(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
}
                

JSON 데이터를 매개변수로 전달하여 이 함수를 호출할 수 있다.

showPrice({symbol: 'IBM', price: 91.42}); // alerts: Symbol: IBM, Price: 91.42
                

이제 Listing 2처럼 이들 두 단계를 웹 페이지에 포함할 수 있는 준비가 완료되었다.


Listing 2. 웹 페이지에 showPrice 함수 및 매개변수 포함하기
<script type="text/javascript">
function showPrice(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
}
</script>
<script type="text/javascript">showPrice({symbol: 'IBM', price: 91.42});</script>

페이지가 로드되면 그림 1과 같은 경고가 표시된다.


그림 1. IBM 티커
IBM ticker

지금까지 이 기사에서는 정적 JSON 데이터를 매개변수로 사용하여 JavaScript 함수를 호출하는 방법을 살펴보았다. 하지만 함수 호출에서 JSON 데이터를 동적으로 랩핑하여 동적 데이터와 함께 함수를 호출할 수도 있다. 이를 동적 JavaScript 삽입 기술이라고 한다. 이 기술의 작동 방법을 확인하려면 ticker.js라는 독립형 JavaScript 파일에 다음 행을 입력해야 한다.

showPrice({symbol: 'IBM', price: 91.42});

이제 웹 페이지의 스크립트를 Listing 3의 코드처럼 변경한다.


Listing 3. 동적 JavaScript 삽입 코드
<script type="text/javascript">
// This is our function to be called with JSON data
function showPrice(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
}
var url = “ticker.js”; // URL of the external script
// this shows dynamic script insertion
var script = document.createElement('script');
script.setAttribute('src', url);

// load the script
document.getElementsByTagName('head')[0].appendChild(script); 
</script>
				

Listing 3의 예제에서, ticker.js에 파일에 있는 동적으로 삽입된 JavaScript 코드는 실제 JSON 데이터를 매개변수로 사용하여 showPrice() 함수를 호출한다.

앞에서 설명한 대로 동일 출처 정책은 동적 스크립트 요소의 문서 내 삽입을 허용하기 때문에 다른 도메인의 JavaScript를 동적으로 삽입하여 JSON 데이터를 전달할 수 있다. 이처럼 함수 호출에 랩핑된 JSON 데이터를 JSONP(JSON with Padding)라고 한다. 이 작업을 수행하려면 코드를 삽입하기 전에 콜백 함수가 미리 정의되어 있어야 한다. 이 예제에서는 showPrice()가 콜백 함수이다.

그러나 JSONP 서비스(또는 원격 JSON 서비스)는 사용자 지정 함수 호출에서 리턴된 JSON 데이터에 대한 랩핑을 지원하는 추가 기능을 가진 웹 서비스이다. 따라서 이 방법을 사용하려면 원격 서비스에서 콜백 함수 이름을 요청 매개변수로 받아야 한다. 그런 다음 원격 서비스에서 JSON 데이터를 매개변수로 전달하는 이 함수에 대한 호출이 생성되면 이 함수가 클라이언트 측 웹 페이지에 삽입되어 바로 실행된다.

jQuery의 JSONP 지원

jQuery 버전 1.2부터는 JSONP 호출에 대한 네이티브 지원이 제공되고 있다. JSONP 콜백을 지정한 경우 다른 도메인에 있는 JSON 데이터를 로드할 수 있으며 JSONP 콜백은 url?callback=?라는 구문을 사용하여 지정할 수 있다.

jQuery에서는 ?가 호출할 생성된 함수 이름으로 자동 변환된다. Listing 4에서는 이 코드를 보여 준다.


Listing 4. JSONP 콜백 사용하기
jQuery.getJSON(url+"&callback=?", function(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
});

이를 위해 jQuery는 스크립트가 삽입될 때 호출되는 전역 함수를 창 오브젝트에 추가한다. 이 함수는 완료 후에 제거된다. jQuery는 도메인 내 호출에 대해서도 최적화 기능을 제공한다. 동일한 도메인에 대한 요청이 발생할 경우 jQuery는 해당 요청을 일반적인 Ajax 요청으로 변환한다.

JSONP 지원을 사용하는 예제 서비스

앞의 예제에서는 정적 파일(ticker.js)을 사용하여 JavaScript를 웹 페이지에 동적으로 삽입했다. JSONP 응답을 리턴하기는 하지만 URL에 콜백 함수 이름을 정의할 수 없었기 때문에 JSONP 서비스가 아니었다. 그렇다면 실제 JSONP 서비스로 변환하려면 어떻게 해야 할까? 이 기사에서는 여러 가지 방법 중에서 PHP와 Java를 사용하는 두 가지 예제를 설명한다.

먼저 서비스에서 요청 URL에 포함된 callback 매개변수를 허용한다고 가정하자. (매개변수 이름 자체는 중요하지 않지만 클라이언트와 서버에서 동일한 이름을 사용해야 한다.) 그리고 서비스에 대한 요청이 다음과 같다고 가정하자.

http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=showPrice

여기에서 symbol은 요청된 티커 기호를 나타내는 요청 매개변수이며, callback은 웹 애플리케이션에서 사용하는 콜백 함수의 이름이다. Listing 5의 코드를 사용하여 jQuery의 JSONP 지원이 포함된 이 서비스를 호출할 수 있다.


Listing 5. 콜백 서비스 호출
jQuery.getJSON("http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=?", 
function(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
});

이 코드에서는 실제 함수 이름 대신 ? 기호를 콜백 함수 이름으로 입력했다. 이는 jQuery가 ? 기호를 인라인 함수를 호출하는 생성된 함수 이름(예: jsonp1232617941775)으로 바꾸기 때문이다. 이 기능을 활용하면 showPrice()와 같은 함수를 자유롭게 정의할 수 있다.

Listing 6에서는 PHP로 구현한 JSONP 서비스의 일부를 보여 준다.


Listing 6. PHP로 구현한 JSONP 서비스의 일부
$jsonData = getDataAsJson($_GET['symbol']);
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});

Listing 7에서는 동일한 기능을 수행하는 Java™ Servlet 메소드를 보여 준다.


Listing 7. Java Servlet으로 구현한 JSONP 서비스
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws ServletException, IOException {
	String jsonData = getDataAsJson(req.getParameter("symbol"));
	String output = req.getParameter("callback") + "(" + jsonData + ");";

	resp.setContentType("text/javascript");
          
	PrintWriter out = resp.getWriter();
	out.println(output);
	// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
}

그렇다면 이제 단일 웹 페이지에 표시하기 위해 써드파티 서버의 컨텐츠를 통합하는 매시업을 빌드하려면 어떻게 해야할까? 간단하다. 써드파티 JSONP 서비스를 사용해야 한다. 이 기사에서는 이들 서비스 중 일부를 소개한다.

바로 사용할 수 있는 JSONP 서비스

이제 JSONP를 사용하는 방법을 알고 있으므로 바로 사용할 수 있는 몇몇 JSONP 웹 서비스로 애플리케이션과 매시업을 빌드해 볼 수 있다. 다음은 후속 개발 프로젝트를 위한 출발점이다. (힌트: 지정된 URL을 브라우저의 주소 필드에 붙여 넣으면 결과 JSONP 응답을 확인할 수 있다.)

Digg API: Digg의 최신 스토리

http://services.digg.com/stories/top?appkey=http%3A%2F%2Fmashup.com&type=javascript
&callback=?

Geonames API: 우편번호에 해당하는 위치 정보

http://www.geonames.org/postalCodeLookupJSON?postalcode=10504&country=US&callback=?

Flickr API: Flickr의 최신 고양이 사진

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any
&format=json&jsoncallback=?
                

Yahoo Local Search API: 우편번호 10504 지역의 피자 검색

http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza
&zip=10504&results=2&output=json&callback=?

주의할 사항

JSONP는 매시업을 빌드하는 데 사용할 수 있는 매우 강력한 기술이기는 하지만 도메인 간 통신에 필요한 모든 요구 사항을 해결할 수 있는 방법은 아니다. 개발 리소스를 확정하기 전에 신중하게 고려해야 하는 단점이 있다. 특히 JSONP 호출에 대한 오류 처리 방법이 없다. 동적 스크립트 삽입이 작동되는 경우에는 함수가 호출되지만 그렇지 않은 경우에는 어떠한 작업도 수행되지 않는다. 즉, 오류도 발생하지 않고 작업만 실패할 뿐이다. 예를 들어, 서버의 404 오류를 받을 수 없다. 요청을 취소하거나 다시 시작할 수도 없다. 그러나 일정 시간이 경과된 후 시간 종료로 요청을 중지할 수 있다. (jQuery의 후속 버전에서는 JSONP 요청에 대한 중단 기능이 지원될 것이다.)

JSONP의 또 다른 주요 단점은 신뢰할 수 없는 서비스와 함께 사용할 경우 매우 위험할 수 있다는 것이다. JSONP 서비스가 함수 호출로 랩핑된 JSON 응답을 리턴하고 브라우저에서 이 응답을 실행하므로 호스트하는 웹 애플리케이션이 다양한 공격에 노출될 수 있다. JSONP 서비스를 사용하려면 내재된 위험 요소를 잘 알고 있어야 한다. 자세한 정보는 참고자료에서 볼 수 있다.



반응형

+ Recent posts