[javascript] 왜 jQuery 인가?

jQuery는 HTML 문서, 보다 정확하게는 문서 개체 모델(DOM)과 자바스크립트 사이의 상호작용을 간단하게 해주는 오픈 소스 자바스크립트 라이브러리이다.

jQuery는 오픈소스이고, 작으며(최소화버전 18KB),  웹브라우저 간의 차이를 표준화하고, 깔끔한 플러그인 아키텍처를 사용하여 경량으로 제작되었고, 플러그인의 자료실(http://plugin.jquery.com)은 광범위하며, 출시 이후 꾸준히 성장하고 있다.
API는 인라인 코드 예제를 포함하여 완전하게 문서화되어 있고, 몇년동안이나 훌륭하게 유지되고 있으며, 상당히 친화적(다른 자바스크립트 라이브러리와의 충돌을 피하는 여러방법을 제공한다. ) 이다.
커뮤니티 지원은 여러 메일링 목록, IRC 채널 그리고 jQuery 커뮤니티의 수 많은 튜토리얼, 아티클, 그리고 플로그의 포스트들을 포함하기에 실제로 꽤 유용하다.
공개적으로 개발되고 있으며, jQuery 개발팀이 업데이트에 대한 출시를 두려워하지 않기 때문에 꾸준하고 일관적이다.
큰 조직(예를 들어 Microsoft, Dell, CBS...)에서 jQuery를 사용하는 것은 꾸준히 늘어날 것이며, 오래도록 지속될 것이다.
브라우저보다도 앞서 W3C의 명세를 수용하고 있다. 일례로 CSS3 셀렉터의 대부분을 지원한다.
최신 브라우저에서 개발을 위한 테스트 및 최적화를 수행하였다.
개발자뿐만 아니라 디자이너에게도 상당히 강력하다. 차별적이지 않다.
자바스크립트의 작성 방식을 바꾸고 있는 jQuery의 간결함, 방법론 그리고 철학은 그 자체가 표준이 되어가고 있다.

jQuery 철학
- "Write less, do more(적게 작성하고, 보다 많이 한다. )"
* 몇몇 요소를 찾아서 (CSS Selector 를 이용해서)  그들로 어떤 작업을 수행한다.(jQuery 메서드를 사용하여).
* 요소의 집합에 대해 여러 jQuery  메서드를 체인으로 연결한다.
* jQuery 래퍼와 암시적인 반복을 사용한다.
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/06/30 18:02 2011/06/30 18:02
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6271

[JSON] json text to json Object

json text를 json object로 바꿀때.

Json.parse() 를 사용한다. 단, json2.js 가 필요하다.

json.stirngify()는 오브젝트를 텍스트로 변환한다.
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/06/28 16:15 2011/06/28 16:15
, ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6263

[javascript] loopedSlider

loopedSlider


https://github.com/nathansearles/loopedSlider
http://slidesjs.com/

loopedSlider 0.5.7 – No longer in development

Check out the next version of loopedSlider, now called Slides https://github.com/nathansearles/Slides

loopedSlider is a plugin made for jQuery that solves a simple problem, the looping of slide content. It was created to be easy to implement, smooth and most of all end the “content rewind” that most other content sliders suffer from.


Info

Check out the next version of loopedSlider, now called Slides http://slidesjs.com

Developed by Nathan Searles, http://nathansearles.com

Complete instructions can be found at http://nathansearles.com/plugin/loopedslider/

For updates, follow Nathan Searles on Twitter

Examples

Markup

<div id="loopedSlider">
	<div class="container">
	        <div class="slides">
	                <div><img src="01.jpg" alt="" /></div>
	                <div><img src="02.jpg" alt="" /></div>
	                <div><img src="03.jpg" alt="" /></div>
	                <div><img src="04.jpg" alt="" /></div>
	        </div>
	</div>
	<a href="#" class="previous">previous</a>
	<a href="#" class="next">next</a>
</div>

CSS

.container { width:500px; height:375px; overflow:hidden; position:relative; cursor:pointer; }
.slides { position:absolute; top:0; left:0; }
.slides div { position:absolute; top:0; width:500px; display:none; }

Initialize

<script type="text/javascript" charset="utf-8">
        $(function(){
                $('#loopedSlider').loopedSlider();
        });
</script>

Defaults

container: ".container", //Class/id of main container. You can use "#container" for an id.
slides: ".slides", //Class/id of slide container. You can use "#slides" for an id.
pagination: "pagination", //Class name of parent ul for numbered links. Don't add a "." here.
containerClick: true, //Click slider to goto next slide? true/false
autoStart: 0, //Set to positive number for true. This number will be the time between transitions.
restart: 0, //Set to positive number for true. Sets time until autoStart is restarted.
hoverPause: false, //Set to true to pause on hover, if autoStart is also true
slidespeed: 300, //Speed of slide animation, 1000 = 1second.
fadespeed: 200, //Speed of fade animation, 1000 = 1second.
autoHeight: 0, //Set to positive number for true. This number will be the speed of the animation.
addPagination: false //Add pagination links based on content? true/false

Defining Local Defaults

<script type="text/javascript" charset="utf-8">
        $(function(){
			$('#loopedSlider').loopedSlider({
				addPagination: true,
				slidespeed: 500
			});
        });
</script>

Defining Global Defaults

<script type="text/javascript" charset="utf-8">
        $(function(){
			$.fn.loopedSlider.defaults.addPagination = true;
			$.fn.loopedSlider.defaults.slidespeed = 500;
        });
</script>
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/06/24 09:44 2011/06/24 09:44
, ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6254

[javascript] iScroll-js

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.

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/05/10 13:06 2011/05/10 13:06
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6149

[javascript] Carousel - Step carousel

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



크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/05/03 19:38 2011/05/03 19:38
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6138

http://wowslider.com/ajax-jquery-slide ··· emo.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- ··· emo.html
http://wowslider.com/ajax-jquery-slide ··· emo.html
http://wowslider.com/jquery-slider-cry ··· emo.html


Recent Demos

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/05/03 19:35 2011/05/03 19:35
, , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6137

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

http://www.ibm.com/developerworks/kr/l ··· sonp1%2F

소개

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 서비스를 사용하려면 내재된 위험 요소를 잘 알고 있어야 한다. 자세한 정보는 참고자료에서 볼 수 있다.



크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/04/28 19:32 2011/04/28 19:32
, , , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6126


About
AmCharts is a set of flash and JavaScript (HTML5) charts for your websites and Web-based products. AmCharts can extract data from simple CSV or XML files, or they can read dynamic data generated with PHP, .NET, Java, Ruby on Rails, Perl, ColdFusion, and many other programming languages.


Blog About JavaScript amCharts – Win an iPad


JavaScript / HTML5 charts

3D Donut Chart
3D Stacked Column
Bar and line
Bars or columns
Bars with gradient fills
Candlestick or OHLC
Chart with legend
Custom bullets
Date Based category axis
Vertical and horizontal guides
Multiple value axes
Pie and column
Pie chart
Rotated axis values
Smoothed line and step

Stock

Data at irregular intervals
OHLC chart
Multiple data sets
Events
Smoothed line chart
Structured products
Vertical legend
Intraday data
Stacked
Drawing trend lines

Column & Bar
Column and line chart mix
3D Stacked column chart
Controlling chart with JavaScript
Chart with gradient fills
Histogram chart
Floating chart
Images above the columns
Columns with rounded corners
Auto-resizing chart

Line & Area

Chart with scroller
Chart with data gaps
Two Y-axes chart
Logarithmic scale chart
Auto-reloading chart
Chart with reversed Y axis

Pie & Donut

2D pie chart
3D donut chart
Saving chart as image
Advanced navigation menus

Scatter & Bubble

Time plot
Chart with value indicator
Bulls eye chart
Error bars
Timeline

Radar & Polar

Stacked radar chart
100% stacked spider chart
Polar chart


크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/04/27 13:29 2011/04/27 13:29
, ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6120

Build mobile web applications with Sencha Touch

An HTML5 mobile JavaScript framework for WebKit browsers
http://www.ibm.com/developerworks/open ··· esources

Overview

In the software development world, two important trends are increasingly important: mobile application development and standards-based HTML5 web development. The learning curve for either type of development can be steep. Developing a native mobile application often requires knowledge of specific platforms and skills, such as Objective-C for iPhone and Java™ for Android (and these are only two platforms). HTML5 development has gained traction lately because it is standards-based. While vendors are working rapidly to incorporate and comply with these early specifications, HTML5 is still rather immature.

The recent release of Sencha Touch 1.0 fuses the cutting-edge worlds of mobile application development with HTML5 web development to form a simple, accessible framework for building mobile web applications. In this article, learn everything you'll need to know to start working with the Sencha Touch framework.


Sencha Touch

Learning to build mobile applications—especially from the perspective of a web developer—can be troublesome. A variety of platforms to choose from and technologies to learn are available. HTML5 support, though gaining momentum quickly, is still not quite ready to be used for complex web applications, particularly line-of-business applications.

Sencha Touch combines the rich platforms of HTML5 and mobile web application development into a happy medium. The framework is developer-friendly and similar to using the Ext JS JavaScript framework. If you have moderate to advanced JavaScript experience, then Sencha Touch is approachable. If you already have skills as a JavaScript and CSS developer, Sencha Touch can immediately turn you into a mobile application developer, too.

Sencha is a company with a core commercial product offering, but it also supports open source software. Sencha Touch 1.0 is free for both personal and commercial use.


Frequently used abbreviations

Ajax: Asynchronous JavaScript + XML
API: application programming interface
CSS: Cascading Style Sheets
HTML: Hypertext Markup Language
JSON: JavaScript Object Notation
SDK: software development kit
UI: user interface

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/04/18 09:22 2011/04/18 09:22
, ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6096

[javascript] JSON의 개요

JSON의 개요 : http://www.json.org/json-ko.html

JSON (JavaScript Object Notation)은 경량의 DATA-교환 형식이다. 이 형식은 사람이 읽고 쓰기에 용이하며, 기계가 분석하고 생성함에도 용이하다. JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999의 일부에 토대를 두고 있다. JSON은 완벽하게 언어로 부터 독립적이지만 C-family 언어 - C, C++, C#, Java, JavaScript, Perl, Python 그외 다수 - 의 프로그래머들에게 친숙한 관습을 사용하는 텍스트 형식이다. 이러한 속성들이 JSON을 이상적인 DATA-교환 언어로 만들고 있다.

JSON은 두개의 구조를 기본으로 두고 있다:

  • name/value 형태의 쌍으로 collection 타입. 다양한 언어들에서, 이는 object, record, struct(구조체), dictionary, hash table, 키가 있는 list, 또는 연상배열로서 실현 되었다.
  • 값들의 순서화된 리스트. 대부분의 언어들에서, 이는 array, vector, list, 또는 sequence로서 실현 되었다.

이러한 것들은 보편적인 DATA 구조이다. 사실상 모든 현대의 프로그래밍 언어들은 어떠한 형태로든 이것들을 지원한다. 프로그래밍 언어들을 이용하여 호환성 있는 DATA 형식이 이러한 구조들을 근간에 두고 있는 것은 당연하다.

JSON 에서, 이러한 형식들을 가져간다:

object는 name/value 쌍들의 비순서화된 SET이다. object는 { (좌 중괄호)로 시작하고 } (우 중괄호)로 끝내어 표현한다. 각 name 뒤에 : (colon)을 붙이고 , (comma)로 name/value 쌍들 간을 구분한다.

array은 값들의 순서화된 collection 이다. array는 [ (left bracket)로 시작해서 ] (right bracket)로 끝내어 표현한다. , (comma)로 array의 값들을 구분한다.

value는 큰따옴표안에 string, number ,true ,false , null, object ,array이 올수 있다. 이러한 구조들을 포함한다.

string은 큰따옴표안에 둘러 싸인 zero 이상 Unicode 문자들의 조합이며, 쌍다옴표안에 감싸지며,backslash escape가 적용된다. 하나의 문자(character)도 하나의 문자열(character string)로서 표현된다. string은 C 또는 Java 문자열 처럼 매우 많이 비슷하다.

number는 8진수와 16진수 형식을 사용하지 않는것을 제외하면 C와 Java number 처럼 매우 많이 비슷하다.

토근들의 어떤 쌍 사이에 공백을 삽입할수 있다. 드물게 encode된 세부 항목을 제외하면, 이렇게 설명된 JSON의 형식은 완벽하게 그 언어를 설명한다.


크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/04/14 10:02 2011/04/14 10:02
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6088

« Previous : 1 : 2 : 3 : 4 : Next »

블로그 이미지

- 홍반장

Archives

Recent Trackbacks

Calendar

«   2024/04   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30        
Statistics Graph

Site Stats

Total hits:
183092
Today:
481
Yesterday:
607