블로그 이미지
Sunny's

calendar

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

Notice

2009. 9. 23. 18:04 Ajax

textarea 에 VS수준의 인텔리센스 기능을 탑재시켜주는 야심찬 계획의 프로토타입 입니다

textareaplus.htm
<%
set db = server.createobject("adodb.connection")
db.open application("connectionstring")
set rs = db.execute("select getdate() as current_time")
%>

textareaplus.v2.htm
<object runat="server" id="db" progid="adodb.connection"></object>
<%
db.Open application("conn")
set cmd = server.CreateObject("adodb.command")
cmd.ActiveConnection = db
cmd.CommandType = adcmdstoredproc
cmd.CommandText = "dbo.usp_some_proc"
cmd.NamedParameters = true
cmd.Parameters.Append cmd.CreateParameter("@return_value",adInteger,adParamReturnValue,,0)
cmd.Parameters.Append cmd.CreateParameter("@param1",adVarChar,adParamInput,10,"param1")
set rs = cmd.Execute
do while not rs.EOF
  response.Write rs(0)
  response.Write "<br>"
  rs.MoveNext
next
rs.Close
set rs = nothing

db.Close
%>




출처 : http://taeyo.net/pds/Content.aspx?SEQ=3121&TBL=UPLOAD&PGN=3
posted by Sunny's
2009. 7. 20. 13:39 Ajax

Goes through the basics of jQuery, all the way up to building plugins.

Original: http://jquery.bassistance.de/jquery-getting-started.html
Author: Jörn Zaefferer

Similar Tutorials: jQuery CoreSelectorsAttributesTraversingManipulationEventsEffectsAjaxPlugins

This guide is an introduction to the jQuery library. Basic knowledge of JavaScript and the document object model (DOM) is required. It starts from ground up and tries to explain details where necessary. It covers a simple hello world example, selector and event basics, AJAX, FX and usage and authoring of plugins.

This guide contains no "click me" examples. The intention of providing only "copy me" code is to invite you to try it for yourself. Copy an example, see what it does, and modify it.

Contents

Setup

To start, we need a copy of the jQuery library, which we can get from the main download page. The jQuery Starterkit provides some markup and CSS to work with. After downloading and extracting its content we put jquery.js into the same directory and open starterkit.html and custom.js with your favorite editor and starterkit.html with a browser.

Now we have everything to start with the notorious "Hello world" example.

Interesting links for this section:

Hello jQuery

We start with an empty html page:

 <html>                                                                  
 <head>                                                                  
 <script type="text/javascript" src="jquery.js"></script>          
 <script type="text/javascript">                                         
   // we will add our javascript code here                                     
 </script>                                                               
 </head>                                                                 
 <body>                                                                  
   <!-- we will add our HTML content here -->                                        
 </body>                                                                 
 </html>

This page just loads the jquery.js library (make sure the URL points to where you stored your copy of jquery! This example assumes that you store it in the same directory as this example file). Two comments indicate where we will expand this template with code.

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

To do this, we register a ready event for the document.

 $(document).ready(function() {
   // do stuff when DOM is ready
 });

Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded. So lets try something a little more sophisticated: Show an alert when clicking a link.

Add the following to the <body>:

 <a href="">Link</a>

Now update the $(document).ready handler:

 $(document).ready(function() {
   $("a").click(function() {
     alert("Hello world!");
   });
 });

This should show the alert as soon as you click on the link. You are ready now to copy and paste this script into your custom.js file. Then, open starterkit.html in the browser and click any link. You should see a pop-up window with "Hello world!" message regardless of what link was clicked.

Let's have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.

This is similar to the following code:

 <a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.

With this in mind, we explore selectors and events a little further.

Interesting links for this section:

Find me: Using selectors and events

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined.

To try some of these selectors, we select and modify the first ordered list in our starterkit.

To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we do it like this:

 $(document).ready(function() {
   $("#orderedlist").addClass("red");
 });

The starterkit provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the first ordered list has a red background. The second list is not modified.

Now lets add some more classes to the child elements of this list.

 $(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });

This selects all child lis of the element with the id orderedlist and adds the class "blue".

Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list.

 $(document).ready(function() {
   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });
 });

There are many other selectors similar to CSS and XPath syntax. More examples and a list of all available expressions can be found here.

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks.

You can find a complete list of all events in the jQuery Events Documentation.

With those selectors and events you can already do a lot of things, but there is more.

 $(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
     $(this).append( " BAM! " + i );
   });
 });

find() allows you to further search the descendants of the already selected elements, therefore $("#orderedlist").find("li") is mostly the same as $("#orderedlist li").

each() iterates over every element and allows further processing. Most methods, like addClass(), use each() themselves.

In this example, append() is used to append some text to it and set it as text to the end of each element.

Another task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

 $(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });

This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

 $(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });

This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.

An additional challenge is to select only certain elements from a group of similar or identical ones. jQuery provides filter() and not() for this. While filter() reduces the selection to the elements that fit the filter expression, not() does the contrary and removes all elements that fit the expression. Think of an unordered list where you want to select all li elements that have no ul children.

 $(document).ready(function() {
   $("li").not(":has(ul)").css("border", "1px solid black"); 
 });

This selects all li elements that have a ul element as a child and removes all elements from the selection. Therefore all li elements get a border, except the one that has a child ul.

The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

 $(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });

This adds a background color to all anchor elements with a name attribute.

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is (Note: This problem was fixed recently in jQuery, available in any versions after 1.1.1). To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

 $(document).ready(function() {
   $("a[href*=/content/gallery]").click(function() {
     // do something with all links that point somewhere to /content/gallery
   });
 });

Until now, all selectors were used to select children or filter the current selection. There are situations where you need to select the previous or next elements, known as siblings. Think of a FAQ page, where all answers are hidden first, and shown, when the question is clicked. The jQuery code for this:

 $(document).ready(function() {
   $('#faq').find('dd').hide().end().find('dt').click(function() {
     $(this).next().slideToggle();
   });
 });

Here we use some chaining to reduce the code size and gain better performance, as '#faq' is only selected once. By using end(), the first find() is undone, so we can start search with the next find() at our #faq element, instead of the dd children.

Within the click handler, the function passed to the click() method, we use $(this).next() to find the next sibling starting from the current dt. This allows us to quickly select the answer following the clicked question.

In addition to siblings, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

 $(document).ready(function(){
   $("a").hover(function(){
     $(this).parents("p").addClass("highlight");
   },function(){
     $(this).parents("p").removeClass("highlight");
   });
 });

For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

Lets go one step back before continuing: jQuery is a lot about making code shorter and therefore easier to read and maintain. The following is a shortcut for the $(document).ready(callback) notation:

 $(function() {
   // code to execute when the DOM is ready
 });

Applied to the Hello world! example, we end with this:

 $(function() {
   $("a").click(function() {
     alert("Hello world!");
   });
 });

Now, with the basics at hand, we want to explore some other aspects, starting with AJAX.

Interesting links for this chapter:

Rate me: Using Ajax

In this part we write a small Ajax application, that allows the user to rate something, just like it is done on youtube.com.

We need some server code for this. My example uses a php file that reads the "rating" parameter and returns the number of ratings and the average rating. Have a look at rate.php for the server-side code.

We don't want this example to work without Ajax, although it may be possible, we therefore generate the necessary markup with jQuery and append it to a container div with an ID of "rating".

 $(document).ready(function() {
   // generate markup
   $("#rating").append("Please rate: ");
   
   for ( var i = 1; i <= 5; i++ )
     $("#rating").append("<a href='#'>" + i + "</a> ");
   
   // add markup to container and apply click handlers to anchors
   $("#rating a").click(function(e){
     // stop normal link click
     e.preventDefault();
     
     // send request
     $.post("rate.php", {rating: $(this).html()}, function(xml) {
       // format and output result
       $("#rating").html(
         "Thanks for rating, current average: " +
         $("average", xml).text() +
         ", number of votes: " +
         $("count", xml).text()
       );
     });
   });
 });

This snippet generates five anchor elements and appends them to the container element with the id "rating". Afterwards, for every anchor inside the container, a click handler is added. When the anchor is clicked, a post request is send to rate.php with the content of the anchor as a parameter. The result returned as a XML is then added to the container, replacing the anchors.

If you don't have a web server with PHP installed at hand, you can look at an online example. For a very nice example of a rating system that even works without JavaScript, visit softonic.de and click on "Kurz bewerten!"

More documentation of the Ajax methods of jQuery can be found in the Ajax Documentation or on Visual jQuery filed under Ajax.

A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function. Example:

 function addClickHandlers() {
   $("a.remote", this).click(function() {
     $("#target").load(this.href, addClickHandlers);
   });
 }
 $(document).ready(addClickHandlers);

Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading.

Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually.

Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:

 // get some data
 var foobar = ...;
 
 // specify handler, it needs data as a paramter
 function handler(data) {
   //...
 }
 
 // add click handler and pass foobar!
 $('a').click(function(){
   handler(foobar);
 });
 
 // if you need the context of the original handler, use apply:
 $('a').click(function(){
   handler.apply(this, [foobar]);
 });

With Ajax this simple we can cover quite a lot of "Web 2.0". Now that we've looked at some basic Ajax, let's add some simple effects and animations to the page.

Interesting links for this chapter:

Animate me: Using Effects

Simple animations with jQuery can be achieved with show() and hide().

 $(document).ready(function(){
   $("a").toggle(function(){
     $(".stuff").hide('slow');
   },function(){
     $(".stuff").show('fast');
   });
 });

You can create any combination of animations with animate(), eg. a slide with a fade:

 $(document).ready(function(){
   $("a").toggle(function(){
     $(".stuff").animate({ height: 'hide', opacity: 'hide' }, 'slow');
   },function(){
     $(".stuff").animate({ height: 'show', opacity: 'show' }, 'slow');
   });
 });

Much fancier effects can be achieved with the interface plugin collection. The site provides demos and documentation. While Interface is at the top of jQuery's plugin list, there are lots of others. The next part shows how to use the tablesorter plugin.

Interesting links for this chapter:

Sort me: Using the tablesorter plugin

The tablesorter plugin allows sorting of tables on the client side. You include jQuery, and the plugin, and tell the plugin which tables you want to sort.

To try this example you need to download the tablesorter plugin and add this line to starterkit.html (below the jquery include):

 <script src="jquery.tablesorter.js"></script>

After including the plugin, you can call it like this:

 $(document).ready(function(){
   $("#large").tablesorter();
 });

Try clicking the headers of the table and see how it is sorted ascending on first click and descending on second.

The table could use some row highlighting, we can add those by passing some options:

 $(document).ready(function() {
   $("#large").tablesorter({
     // striping looking
     widgets: ['zebra']	
   });
 });

There are more examples and documentation about the available options at the tablesorter homepage.

Most plugins can be used like this: Include the plugin file and call the plugin method on some elements, passing some optional settings to customize the plugin.

A up-to-date list of available plugins can be found on the jQuery Plugin site.

When you are using jQuery more often, you may find it useful to package your own code as a plugin, either to reuse it for yourself or your company, or to share it with the community. The next chapter gives some hints on how to structure a plugin.

Interesting links for this chapter:

Plug me: Writing your own plugins

Writing your own plugins for jQuery is quite easy. If you stick to the following rules, it is easy for others to integrate your plugin, too.

Plugin Naming

Find a name for your plugin, lets call our example "foobar". Create a file named jquery.[yourpluginname].js, eg. jquery.foobar.js

Adding a Custom Method

Create one or more plugin methods by extending the jQuery object, eg.:

 jQuery.fn.foobar = function() {
   // do something
 };

Which will then be accessible by performing:

 $(...).foobar();

Default Settings:

Create default settings that can be changed by the user, eg.:

 jQuery.fn.foobar = function(options) {
   var settings = jQuery.extend({
     value: 5, name: "pete", bar: 655
   }, options);
 };

You can then call the plugin without options, using the defaults:

 $("...").foobar();

Or with some options:

 $("...").foobar({ value: 123, bar: 9 });

Documentation

If you release your plugin, you should provide some examples and documentation, too. There are lots of plugins available as a great reference.

Now you should have the basic idea of plugin writing. Lets use this knowledge and write one of our own.

Checkbox Plugin

Something lots of people, trying to manipulate forms with jQuery, ask for, is checking and unchecking of radio buttons or checkboxes. They end up with code like this:

 $("input[@type='checkbox']").each(function() {
   this.checked = true;
   this.checked = false; // or, to uncheck
   this.checked = !this.checked; // or, to toggle
 });

Whenever you have an each in your code, you might want to rewrite that as a plugin, pretty straightforward:

 jQuery.fn.check = function() {
   return this.each(function() {
     this.checked = true;
   });
 };

This plugin can now be used:

 $("input[@type='checkbox']").check();

Now you could write plugins for both uncheck() and toggleCheck(), too. But instead we extend our plugin to accept some options.

 jQuery.fn.check = function(mode) {
   // if mode is undefined, use 'on' as default
   var mode = mode || 'on';
   
   return this.each(function() {
     switch(mode) {
       case 'on':
         this.checked = true;
         break;
       case 'off':
         this.checked = false;
         break;
       case 'toggle':
         this.checked = !this.checked;
         break;
     }
   });
 };

By providing a default for the option, the user can omit the option or pass one of "on", "off", and "toggle", eg.:

 $("input[@type='checkbox']").check();
 $("input[@type='checkbox']").check('on');
 $("input[@type='checkbox']").check('off');
 $("input[@type='checkbox']").check('toggle');

Optional Settings

With more than one optional setting, this approach gets complicated, because the user must pass null values if he wants to omit the first parameter and only use the second.

The use of the tablesorter in the last chapter demonstrates the use of an object literal to solve this problem. The user can omit all parameters or pass an object with a key/value pair for every setting he wants to override.

For an exercise, you could try to rewrite the Voting code from the fourth section as a plugin. The plugin skeleton should look like this:

 jQuery.fn.rateMe = function(options) {
   // instead of selecting a static container with 
   // $("#rating"), we now use the jQuery context
   var container = this;
   
   var settings = jQuery.extend({
     url: "rate.php"
     // put more defaults here
   }, options);
   
   // ... rest of the code ...
   
   // if possible, return "this" to not break the chain
   return this;
 });

And allowing you to run the plugin like so:

 $(...).rateMe({ url: "test.php" });
posted by Sunny's
2009. 7. 20. 13:34 Ajax

Jesse Skinner, Web Developer, Freelance

2007 년 9 월 04 일

jQuery는 JavaScript 라이브러리로서 JavaScript™와 Asynchronous JavaScript + XML (Ajax) 프로그래밍을 단순화 하는데 도움이 됩니다. JavaScript 라이브러리와는 달리, jQuery는 복잡한 코드를 간결하게 표현할 수 있는 독특한 철학이 있습니다. jQuery 원리, 기능과 특징을 배우고, 일반적인 Ajax 태스크도 수행하며, 플러그인으로 jQuery를 확장하는 방법도 알아봅니다.

jQuery란 무엇인가?

2006년 초, John Resig가 만든 jQuery는 JavaScript 코드로 작업하는 사람들에게는 훌륭한 라이브러리이다. 여러분이 JavaScript 언어 초보자라서 라이브러리가 Document Object Model (DOM) 스크립팅과 Ajax의 복잡성을 다루어주기를 원하든지, 숙련된 JavaScript 구루로서 DOM 스크립팅과 Ajax의 반복성에 지루해졌다면, jQuery가 제격이다.

jQuery는 코드를 단순하고 간결하게 유지한다. 많은 반복 루프와 DOM 스크립팅 라이브러리 호출을 작성할 필요가 없다. jQuery를 사용하면 매우 적은 문자로 표현할 수 있다.

jQuery 철학은 매우 독특하다. 무엇이든 단순하고 재사용 가능한 것으로 유지하기 위해 디자인 되었다. 여러분이 이러한 철학을 이해하고 여기에 편안함을 느낀다면, jQuery가 여러분의 프로그래밍 방식을 충분히 향상시킬 수 있다.




위로


단순화

다음은 jQuery가 여러분의 코드에 어떤 영향을 미치는지를 보여주는 예제이다. 페이지의 모든 링크에 클릭 이벤트를 붙이는 것 같이 단순하고 일반적인 것을 수행하려면, 플레인 JavaScript 코드와 DOM 스크립팅을 사용하는 것이 낫다. (Listing 1)


Listing 1. jQuery 없는 DOM 스크립팅
                
var external_links = document.getElementById('external_links');
var links = external_links.getElementsByTagName('a');
for (var i=0;i < links.length;i++) {
    var link = links.item(i);
    link.onclick = function() {
        return confirm('You are going to visit: ' + this.href);
    };
}

Listing 2는 같은 기능에 jQuery를 사용한 모습이다.


Listing 2. jQuery를 사용한 DOM 스크립팅
                
$('#external_links a').click(function() {
    return confirm('You are going to visit: ' + this.href);
});

놀랍지 않은가? jQuery를 사용하면 복잡하지 않게 코드로 표현하고자 하는 것만 나타낼 수 있다. 엘리먼트를 반복할 필요가 없다. click() 함수가 이 모든 것을 관리한다. 또한, 다중 DOM 스크립팅 호출도 필요 없다. 여기에서 필요한 것은 엘리먼트가 어떻게 작동하는지를 설명하는 짧은 스트링이다.

이 코드로 어떻게 작업이 수행되는지를 이해하기는 조금 어렵다. 우선, $() 함수가 있어야 한다. 이것은 jQuery에서 가장 강력한 함수이다. 대게, 이 함수를 사용하여 문서에서 엘리먼트를 선택한다. 이 예제에서, 이 함수는 Cascading Style Sheets (CSS) 신택스를 포함하고 있는 스트링으로 전달되고, jQuery는 효율적으로 이 엘리먼트를 찾는다.

CSS 셀렉터의 기본을 이해하고 있다면, 이 신택스가 익숙할 것이다. Listing 2에서, #external_linksexternal_linksid를 가진 엘리먼트를 찾는다. a 앞에 있는 공간은 jQuery에게 external_links 엘리먼트 내의 모든 <a> 엘리먼트를 찾도록 명령한다. 영어와 DOM은 장황하지만, CSS에서는 매우 간단하다.

$() 함수는 CSS 셀렉터와 매치하는 모든 엘리먼트를 포함하고 있는 jQuery 객체를 리턴한다. jQuery 객체는 어레이와 비슷하지만, 수 많은 특별한 jQuery 함수들이 포함된다. 예를 들어, click 함수를 호출함으로써 클릭 핸들러 함수를 jQuery 객체의 각 엘리먼트에 할당할 수 있다.

또한, 엘리먼트나 엘리먼트의 어레이를 $() 함수로 전달하면, 이것은 엘리먼트 주위에 jQuery 객체를 래핑할 것이다. 이 기능을 사용하여 window 객체 같은 것에 jQuery 함수를 적용하고 싶을 것이다. 일반적으로 이 함수를 다음과 같이 로드 이벤트에 할당한다.

window.onload = function() {
    // do this stuff when the page is done loading
};

jQuery를 사용하면, 같은 코드도 다음과 같이 된다.

$(window).load(function() {
    // run this when the whole page has been downloaded
});

이미 알고 있었겠지만, 윈도우가 로딩하기를 기다리는 일은 매우 지루한 일이다. 전체 페이지가 로딩을 끝마쳐야 하기 때문이다. 여기에는 페이지의 모든 이미지들도 포함된다. 가끔, 이미지 로딩을 먼저 끝내고 싶지만, 대부분의 경우 Hypertext Markup Language (HTML)만 로딩해야 한다. jQuery는 문서에 특별한 ready 이벤트를 만듦으로써 이 문제를 해결한다.

$(document).ready(function() {
    // do this stuff when the HTML is all ready
});

이 코드는 document 엘리먼트 주위에 jQuery 객체를 만들고, HTML DOM 문서가 준비될 때 함수를 설정하여 인스턴스를 호출한다. 이 함수를 필요한 만큼 호출할 수 있다. 진정한 jQuery 스타일에서, 지름길은 이 함수를 호출하는 것이다. 함수를 $() 함수로 전달한다.

$(function() {
    // run this when the HTML is done downloading
});

지금까지, $() 함수를 사용하는 세 가지 방법을 설명했다. 네 번째 방법은, 스트링을 사용하여 엘리먼트를 만드는 것이다. 결과는, 그 엘리먼트를 포함하고 있는 jQuery 객체가 된다. Listing 3은 문단을 페이지에 추가하는 예제이다.


Listing 3. 간단한 문단을 생성하여 붙이기
                
$('<p></p>')
    .html('Hey World!')
    .css('background', 'yellow')
    .appendTo("body");

이전 예제에서 파악했겠지만, jQuery의 또 다른 강력한 기능은 메소드 체인(method chaining.)이다. jQuery 객체에 대해 메소드를 호출할 때마다, 이 메소드는 같은 jQuery 객체를 리턴한다. jQuery 객체에 다중 메소드를 호출하고 싶다면 셀렉터를 다시 입력하지 않고 이를 수행할 수 있다.

$('#message').css('background', 'yellow').html('Hello!').show();




위로


Ajax로 단순하게!

Ajax는 jQuery를 사용하면 더 단순해 질 수 있다. jQuery에는 쉬운 것도 쉽게 복잡한 것도 가능한 단순하게 만드는 유용한 함수들이 많이 있다.

Ajax에서 사용되는 방식은 HTML 청크를 페이지 영역에 로딩하는 것이다. 여러분이 필요로 하는 엘리먼트를 선택하고 load() 함수를 사용하는 것이다. 다음은 통계를 업데이트 하는 예제이다.

$('#stats').load('stats.html');

일부 매개변수들을 서버 상의 페이지로 전달해야 할 경우가 종종 있다. jQuery를 사용하면 이는 매우 간단하다. 필요한 메소드가 어떤 것인지에 따라서 $.post()$.get() 중 선택한다. 선택적 데이터 객체와 콜백 함수를 전달할 수도 있다. Listing 4는 데이터를 보내고 콜백을 사용하는 예제이다.


Listing 4. Ajax를 사용하여 데이터를 페이지로 보내기
                
$.post('save.cgi', {
    text: 'my string',
    number: 23
}, function() {
    alert('Your data has been saved.');
});

복잡한 Ajax 스크립팅을 해야 한다면, $.ajax() 함수가 필요하다. xml, html, script, json을 지정할 수 있고, 여러분이 바로 사용할 수 있도록 jQuery가 자동으로 콜백 함수에 대한 결과를 준비한다. 또한, beforeSend, error, success, complete 콜백을 지정하여 사용자에게 Ajax에 대한 더 많은 피드백을 제공할 수 있다. 게다가, Ajax 요청의 타임아웃이나 페이지의 "최종 변경" 상태를 설정하는 매개변수들도 있다. Listing 5는 필자가 언급했던 매개변수를 사용하여 XML 문서를 검색하는 예제이다.


Listing 5. $.ajax()를 사용하여 복잡한 Ajax를 단순하게
                
$.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'xml',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});

콜백 성공으로 XML을 받으면, jQuery를 사용하여 HTML에서 했던 것과 같은 방식으로 XML을 볼 수 있다. 이는 XML 문서 작업을 쉽게 하며 콘텐트와 데이터를 웹 사이트로 쉽게 통합시킨다. Listing 6은 리스트 아이템을 XML의 <item> 엘리먼트용 웹 페이지에 추가하는 success 함수에 대한 확장 모습이다.


Listing 6. jQuery를 사용하여 XML 작업하기
                
success: function(xml){
    $(xml).find('item').each(function(){
        var item_text = $(this).text();

        $('<li></li>')
            .html(item_text)
            .appendTo('ol');
    });
}




위로


HTML 애니메이션

jQuery를 사용하여 기본적인 애니메이션과 효과를 다룰 수 있다. 애니메이션 코드의 중심에는 animate() 함수가 있는데, 이는 숫자로 된 CSS 스타일 값을 바꾼다. 예를 들어, 높이, 넓이, 폭, 위치를 움직일 수 있다. 또한, 애니메이션의 속도를 밀리초 또는 사전 정의된 속도(느림, 보통, 빠름)로 지정할 수 있다.

다음은, 엘리먼트의 높이와 넓이를 동시에 움직이게 하는 예제이다. 시작 값은 없고 종료 값만 있다. 시작 값은 엘리먼트의 현재 크기에서 가져온다. 여기에도 콜백 함수를 첨부했다.

$('#grow').animate({ height: 500, width: 500 }, "slow", function(){
    alert('The element is done growing!');
});

jQuery는 빌트인 함수를 사용하여 일반적인 애니메이션도 더욱 쉽게 만든다. show()hide() 엘리먼트를 즉각적으로 또는 지정된 속도로 사용할 수 있다. fadeIn()fadeOut() 또는 slideDown()slideUp()을 사용하여 엘리먼트를 나타나게 하거나 사라지게 할 수 있다. 다음은 네비게이션의 slidedown 예제이다.

$('#nav').slideDown('slow');




위로


DOM 스크립팅과 이벤트 핸들링

jQuery는 DOM 스크립팅과 이벤트 핸들링을 단순화하는데 제격이다. DOM의 트래버스와 조작이 쉽고, 이벤트의 첨부, 제거, 호출은 매우 자연스러운 일이며, 직접 수행하는 것보다 에러도 적게 발생한다.

기본적으로 jQuery는 DOM 스크립팅으로 수행하는 일들을 더욱 쉽게 수행할 수 있도록 해준다. 엘리먼트를 생성하고 append() 함수를 사용하여 이들을 다른 엘리먼트로 연결할 수 있고, clone()을 사용하여 엘리먼트를 중복시키고, 콘텐트를 html()로 설정하고, empty() 함수로 콘텐트를 삭제하고, remove() 함수로 엘리먼트를 삭제하고, wrap() 함수를 사용하여 또 다른 엘리먼트로 엘리먼트를 래핑한다.

DOM을 트래버스 함으로써 jQuery 객체의 콘텐트를 변경할 때 여러 함수들을 사용할 수 있다. 엘리먼트의 siblings(), parents(), children()을 사용할 수 있다. 또한, next() 또는 prev() sibling 엘리먼트도 선택할 수 있다. 아마도 가장 강력한 것은 find() 함수일 것이다. jQuery 셀렉터를 사용하여 jQuery 객체의 엘리먼트 종속 관계들을 통해 검색할 수 있다.

이 함수는 end() 함수와 사용될 때 더욱 강력해진다. 이 함수는 실행 취소 함수와 비슷하고, find() 또는 parents() 또는 다른 트래버싱 함수들을 호출하기 전에 가졌던 jQuery 객체로 돌아간다.

메소드 체인과 함께 사용되면, 복잡한 연산도 단순하게 보이게 할 수 있다. Listing 7은 로그인 폼을 찾고 이와 관련한 여러 엘리먼트를 조작하는 예제이다.


Listing 7. DOM의 트래버스와 조작
                
$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()

    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()

    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });

믿을 수 있는지 모르겠지만, 이 예제는, 공백을 사용한 하나의 연결된 코드 라인일 뿐이다. 우선, 로그인 폼을 선택했다. 그리고 나서, 이 안에 선택 레이블을 찾고, 이들을 숨긴 다음, end()를 호출하여 폼으로 돌아가게 하였다. 패스워드 필드를 찾았고, 보더를 빨간색으로 한 다음, 다시 end()를 호출하여 폼으로 돌아갔다. 마지막으로, 제출 이벤트 핸들러를 폼에 추가했다. 여기에서 특히 재미있는 부분은 jQuery가 모든 쿼리 연산들을 최적화 하기 때문에, 여러분은 모든 것이 서로 잘 연결될 때 엘리먼트를 두 번 찾을 필요가 없다.

공통 이벤트 핸들링은 click(), submit(), mouseover() 같은 함수를 호출하고 여기에 이벤트 핸들러 함수를 전달하는 것만큼 단순하다. 게다가, bind('eventname', function(){})을 사용하여 커스텀 이벤트 핸들러를 할당하는 옵션도 있다. unbind('eventname')를 사용하여 특정 이벤트를 제거하거나, unbind()를 사용하여 모든 이벤트를 제거할 수 있다. 이것과 기타 함수들을 사용하는 다른 방법들은, jQuery 애플리케이션 프로그램 인터페이스(API) 문서를 참조하라. (참고자료)




위로


jQuery 셀렉터의 힘 활용하기

#myid 같은 아이디 또는 div.myclass 같은 클래스 이름으로 엘리먼트를 선택한다. 하지만, jQuery는 하나의 셀렉터에서 거의 모든 엘리먼트 조합을 선택할 수 있도록 하는 복잡하고도 완벽한 셀렉터 신택스를 갖고 있다.

jQuery의 셀렉터 신택스는 CSS3과 XPath에 기반하고 있다. CSS3과 XPath 신택스를 더욱 잘 안다면, jQuery 사용이 더욱 수월해진다. CSS와 XPath를 포함하여 jQuery 셀렉터의 전체 리스트를 보려면 참고자료 섹션을 참조하라.

CSS3에는 모든 브라우저가 지원하지 않는 신택스가 포함되어 있기 때문에, 이를 자주 볼 수 없다. 하지만, jQuery에서 CSS3을 사용하여 엘리먼트를 선택한다. jQuery는 고유의 커스텀 셀렉터 엔진을 갖고 있다. 예를 들어, 테이블의 모든 빈 컬럼 안에 대시(dash)를 추가하려면, :empty pseudo-selector를 사용한다.

$('td:empty').html('-');

특정 클래스를 갖고 있지 않은 모든 엘리먼트를 찾는다면? CSS3은 이를 위한 신택스도 있다. :not pseudo-selector를 사용하는 것이다. 다음은 required의 클래스를 갖고 있지 않은 모든 인풋을 숨기는 방법이다.

$('input:not(.required)').hide();

또한, CSS에서처럼 다중 셀렉터를 콤마를 사용하여 하나로 연결시킬 수 있다. 다음은 이 페이지에서 모든 리스트 유형들을 동시에 숨기는 예제이다.

$('ul, ol, dl').hide();

XPath는 하나의 문서에서 엘리먼트를 찾는 강력한 신택스이다. CSS와는 다르며, CSS로 수행할 수 없는 몇 가지 일을 수행할 수 있다. 보더를 모든 체크 박스의 부모 엘리먼트에 추가하려면, XPath의 /.. 신택스를 사용할 수 있다.

$("input:checkbox/..").css('border', '1px solid #777');

가독성 있는 테이블을 만들려면, 다른 클래스 이름을 테이블의 모든 짝수 또는 홀수 행에 붙인다. 이를 다른 말로 테이블의 스트라이핑(striping)이라고 한다. jQuery를 사용하면 :odd pseudo-selector 덕택에 쉽게 수행할 수 있다. 아래 예제는 테이블의 모든 홀수 행의 백그라운드를 striped 클래스를 사용하여 변경한다.

$('table.striped > tr:odd').css('background', '#999999');

jQuery 셀렉터로 코드를 어느 정도 단순화 할 수 있는지를 보았다. 어떤 엘리먼트를 선택하든지 간에, 하나의 jQuery 셀렉터를 사용하여 이를 정의하는 방법도 찾을 수 있다.




위로


플러그인으로 jQuery 확장하기

대부분의 소프트웨어와는 달리, jQuery용 플러그인 작성은 복잡한 API를 사용해야 하는 힘든 일이 아니다. 사실, jQuery 플러그인은 작성하기가 쉬워서 몇 가지만 작성하면 코드를 더욱 단순하게 유지할 수 있다. 다음은 여러분이 작성할 수 있는 가장 기본적인 jQuery 플러그인이다.

$.fn.donothing = function(){
    return this;
};

단순하지만, 이 플러그인은 약간의 설명이 필요하다. 우선, 함수를 모든 jQuery 객체에 추가하려면, 여기에 $.fn을 할당하고, 이 함수는 this (jQuery 객체)를 리턴하여 이것이 메소드 체인을 깨트리지 않도록 해야 한다.

이 예제를 기반으로 쉽게 구현할 수 있다. css('background')를 사용하는 대신 플러그인을 작성하여 백그라운드를 바꾸려면, 다음을 사용한다.

$.fn.background = function(bg){
    return this.css('background', bg);
};

css()에서 값을 리턴할 뿐이다. 이것은 이미 jQuery 객체를 리턴하기 때문이다. 따라서, 메소드 체인은 여전이 잘 작동한다.

여러분은 반복 작업이 있을 경우에 jQuery 플러그인을 사용하기 바란다. 예를 들어, 같은 일을 여러 번 수행하기 위해 each() 함수를 사용하고 있다면 플러그인을 사용해도 된다.

jQuery 플러그인을 작성이 쉽기 때문에, 여러분이 사용할 수 있는 것도 수백 가지나 존재한다. jQuery는 탭, 곡선형 코너, 슬라이드 쇼, 툴 팁, 날짜 셀렉터, 기타 여러분이 상상하고 있는 모든 것을 위한 플러그인이 있다. 플러그인 리스트는 참고자료 섹션을 참조하기 바란다.

가장 복잡하고 광범위하게 사용되는 플러그인은 Interface이다. 이것은 정렬, 드래그&드롭 기능, 복합 효과, 기타 복잡한 사용자 인터페이스(UI)를 핸들하는 애니메이션 플러그인이다. Interface가 jQuery를 위한 것이라면 Prototype에는 Scriptaculous가 있다.

또한 Form 플러그인도 대중적이고 유용하다. 이것으로 Ajax를 사용하여 백그라운드에서 폼을 쉽게 제출할 수 있다. 이 플러그인은 폼의 제출 이벤트를 하이재킹 하고, 다른 인풋 필드를 찾고, 이들을 사용하여 Ajax 호출을 구현하는 상황에 사용된다.




위로


jQuery 이후의 삶

jQuery를 사용하여 할 수 있는 것의 표면적인 부분만 다루었다. jQuery는 기분 좋게 사용할 수 있고 새로운 트릭이나 기능도 자연스럽다. jQuery는 JavaScript와 Ajax 프로그래밍을 매우 단순화 시킬 수 있다. 새로운 것을 배울 때마다 코드는 더욱 단순해 진다.

jQuery를 배운 후에, 필자는 JavaScript 언어로 하는 프로그래밍에 재미를 발견했다. 지루한 부분은 알아서 처리되기 때문에, 필자는 중요한 코딩 부분에만 집중하면 된다. jQuery를 사용하게 되면서 지난날 for 루프를 작성하던 때는 거의 기억이 나지 않는다. 심지어, 다른 JavaScript 라이브러리를 사용할 생각도 거의 하지 않는다. jQuery는 JavaScript 프로그래밍 방식을 진정으로 바꿔 놓았다.



참고자료

교육

제품 및 기술 얻기

토론


필자소개

Photo of Jesse Skinner

Jesse

 

posted by Sunny's
2009. 7. 20. 10:53 Ajax

조작하려는 엘리먼트 선택하기

전 장에서도 간단히 살펴보았지만 우선 jQuery매소드를 사용하기 위해선 페이지에서 조작할 엘리먼트를 선택해야 한다. 여기선 이런 엘리먼트를 선택하는 방법에 대해 알아보자.
  • 기본 CSS 선택자를 이용해 선택하기
  • 위치로 선택하기
  • jQuery 정의 선택자로 선택하기
위의 세가지 방법을 이용해 엘리먼트를 선택하는 것에 대해 알아보자.

기본 CSS 선택자 사용하기

CSS를 사용해 본 유저라면 이 선택 기법은 익숙할 것이다.엘리먼트의 ID, CSS 클래스명, 태그명, 페이지 엘리먼트의 DOM 계층 구조를 이용해 엘리먼트를 선택하는 기법이 그것들이며 아래의 예를 보자.
  • a - 모든 링크 엘리먼트와 일치하는 선택자
  • #specialID - specialID를 아이디로 가지는 엘리먼트와 일치하는 선택자
  • .specialClass - specialClass를 클래스로 가지는 모든 엘리먼트와 일치하는 선택자
  • a#specialID.specialClass - 아이디가 specialID이고 specialClass를 클래스로 가지는 링크와 일치하는 선택자
  • p a.specialClass - 단락 엘리먼트 내에 선언되고 specialClass를 클래스로 가지는 모든 링크와 일치하는 선택자
이러한 기존의 CSS 선택자를 이용하여 엘리먼트를 선택할 수 있게 되는데, jQuery가 지원하는 선택자들은 아래와 같다.
선택자내 용
*모든 엘리먼트
E태그명이 E인 모든 엘리먼트
E FE의 자손이면서 태그명이 F인 모든 엘리먼트
E>FE의 바로 아래 자식이면서 태그명이 F인 모든 엘리먼트
E+FE의 형제 엘리먼트로 바로 다음에 나오는 엘리먼트 F
E~FE의 형제 엘리먼트로 다음에 나오는 모든 엘리먼트 F
E:has(F)태그명이 F인 자손을 하나 이상 가지는 태그명이 E인 모든 엘리먼트
E.C클래스명 C를 가지는 모든 엘리먼트 E
E#I아이디가 I인 엘리먼트 E
E[A]속성 A를 가지는 모든 엘리먼트 E
E[A=V]값이 V인 속성 A를 가지는 모든 엘리먼트 E
E[A^=V]값이 V로 시작하는 속성 A를 가지는 모든 엘리먼트 E
E[A$=V]값이 V로 끝나는 속성 A를 가지는 모든 엘리먼트 E
E[A*=V]값이 V를 포함하는 속성 A를 가지는 모든 엘리먼트 E
위의 선택자를 활용하는 방법에 대해 예제를 통해 알아보자.(예제보기)

위치로 선택하기

때로는 페이지에 있는 엘리먼트 위치나 다른 엘리먼트와 연관된 관계를 기반으로 엘리먼트를 선택해야 한다. 예를 들어 페이지에서 첫 번째 링크나 홀수 및 짝수 번째 문단 등을 선택하는 기법이 필요할 때가 있다. 이에 대해 정리한 것이 아래의 표이다.
선택자설 명
:first페이지에서 처음으로 일치하는 엘리먼트
:last페이제에서 마지막으로 일치하는 엘리먼트
:first-child첫 번째 자식 엘리먼트
:last-child마지막 자식 엘리먼트
:only-child형제가 없는 모든 엘리먼트를 반환
:nth-child(n)n번째 자식 엘리먼트
:nth-child(even|odd)짝수 혹은 홀수 자식 엘리먼트
:nth-child(Xn+Y)전달된 공식에 따른 n번째 자식 엘리먼트
:even / :odd페이지 전체의 짝수/홀수 엘리먼트
:eq(n)n번째로 일치하는 엘리먼트
:gt(n)n번째 엘리먼트 이후의 엘리먼트와 일치
:lt(n)n번째 엘리먼트 이전의 엘리먼트와 일치

jQuery 정의 선택자 사용하기

CSS 선택자를 이용해 우리는 원하는 DOM 엘리먼트를 선택할 수 있었지만 때로는 이것만으로 표현할 수 없는 특성이 있는 엘리먼트를 선택해야 한다. 예를 들어 라디어 버튼 중 check가 된 엘리먼트만을 선택하기에는 CSS선택자만으로는 부족하다. 이렇듯 부족한 부분을 jQuery 정의 선택자를 이용하여 채울 수 있다.
선택자설 명
:animated현재 애니메이션이 적용되고 있는 엘리먼트
:button모든 버튼을 선택
:checkbox체크박스 엘리먼트 선택
:checked선택된 체크박스나 라디오 버튼을 선택
:contains(foo)텍스트 foo를 포함하는 엘리먼트 선택
:disabled인터페이스에서 비활성화 상태인 모든 폼 엘리먼트를 선택
:enabled인터페이스에서 활성화 상태인 모든 폼 엘리먼트를 선택
:file모든 파일 엘리먼트를 선택
:header헤더 엘리먼트 선택
:hidden감춰진 엘리먼트 선택
:image폼 이미지를 선택
:input폼 엘리먼트만 선택
:not(filter)필터의 값을 반대로 변경
:parent빈 엘리먼트를 제외하고, 텍스트도 포함해서 자식 엘리먼트를 가지는 엘리먼트
:password패스워드 엘리먼트 선택
:radio라디오 버튼 엘리먼트 선택
:reset리셋 버튼을 선택
:selected선택된 엘리먼트 선택
:submit전송 버튼을 선택
:text텍스트 엘리먼트 선택
:visible보이는 엘리먼트 선택
여러 jQuery 정의 선택자가 폼과 관련되며 덕분에 특정 엘리먼트의 타입이나 상태를 세련되게 표현할 수 있다. 선택자 필터도 조합할 수 있다. 예를 들어 활성화 되고 선택된 체크박스만 일치시키려 한다면 다음과 같다.
 
 
:checkbox:checked:enabled

새로운 HTML 생성하기

jQuery() 함수는 페이지의 엘리먼트를 선택할 뿐 아니라 새로운 HTML을 생성할 수도 있다.
 
$("<div>안녕</div>")
이 표현식은 페이지에 추가할 새로운 <div> 엘리먼트를 생성한다. 다음의 코드를 이용하여 <div> 엘리먼트를 두 개 생성해보자.
 

$("<div class='foo'>내가 foo를 가졌다.</div><div>나는 foo를 가지지 않았다.")

.filter(".foo").click(function(){ alert("내가 foo이다."); })

.end().appendTo("#someParentDiv");

위의 코드는 <div> 엘리먼트를 생성하는데 첫번째 <div> 엘리먼트는 foo 클래스가 있고, 다른 하나에는 없다. 생성한 첫번째 <div> 엘리먼트를 클릭하면 alert()가 실행된다. 마지막으로 end()메서드를 이용해 필터링 이전의 두 <div>엘리먼트를 지닌 집합으로 돌아간 뒤, 이 집합을 id가 someParentDiv인 엘리먼트에 덧붙인다.
posted by Sunny's
2009. 4. 16. 17:34 Ajax

Data types, syntax and example
  • Number (integer, real, or floating point)
  • String (double-quoted Unicode with backslash escaping)
  • Boolean (true and false)
  • Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
  • Object (collection of key:value pairs, comma-separated and enclosed in curly braces)
  • null
  • {
         "firstName": "John",
         "lastName": "Smith",
         "address": {
             "streetAddress": "21 2nd Street",
             "city": "New York",
             "state": "NY",
             "postalCode": 10021
         },
         "phoneNumbers": [
             "212 555-1234",
             "646 555-4567"
         ]
    }

    Using JSON in Ajax
    var the_object;
    var http_request = new XMLHttpRequest();
    http_request.open( "GET", url, true );
    http_request.send(null);
    http_request.onreadystatechange = function () {
        if ( http_request.readyState == 4 ) {
            if ( http_request.status == 200 ) {
                the_object = eval( "(" + http_request.responseText + ")" );
            } else {
                alert( "There was a problem with the URL." );
            }
            http_request = null;
        }
    };


    Security issues

    var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
    text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
    eval('(' + text + ')');


    출처 : http://en.wikipedia.org/wiki/JSON
    샘플 :

    ASP로 JSON 만들기

    <!--#include file="JSON_2.0.2.asp"-->
    <!--#include file="JSON_UTIL_0.1.1.asp"-->
    <%

    Dim Result
    Set member = jsObject()
    member("aresult") = "1"
    member("amsg") = "사용가능한 아뒤"
    member.Flush   


    'QueryToJSON(dbconn, "SELECT name, surname FROM members WHERE age < 30").Flush  '--> 가능
     %>


    JSON 사용하기

    <script language="JavaScript" src="xmlhttp.js"></script>
    <script language="javascript" type="text/javascript">
    function xml_IDCheck() {
     var xmlHttpID = Ajax.getTransport();
     
     var obj = document.getElementById("m_id");
     var m_id = obj.value;
     if (m_id == ""){
      alert('아이디를 입력 하세요');
      obj.focus();
      return;
     }else{
      xmlHttpID.Open("GET", "id_check_JSON.asp?m_id="+m_id, true);
      xmlHttpID.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlHttpID.onreadystatechange = xml_IDCallback;
      xmlHttpID.send(null);
     }

     function xml_IDCallback() {
      var obj = document.getElementById("m_id");
      if (xmlHttpID.readyState == 4) {
       if (xmlHttpID.status == 200) {
           xmlDoc = xmlHttpID.responseXML;

           var data = eval("(" + xmlHttpID.responseText + ")");


           try {
              
            var result = data.aresult;
            var msg = data.amsg;

        } catch(e) {
         return;
        }
        if (result == "1"){
         alert(msg);
         return;  
        } else if (result == "0"){
         alert(msg);
         obj.value = "";
         obj.focus();
         return;    
        }
       } else if (xmlHttpID.status == 204) {
        alert("전달된 데이터가 없습니다");
       } else if (xmlHttpID.status == 404) {
        alert("URL을 확인하세요");
       } else if (xmlHttpID.status == 500) {
        alert("내부 에러");
       }
      }
     }
    }

    </script>

    <body>
      <form action="test.asp">
       <p>test:
        <input type="text" size="14" name="m_id" onChange="xml_IDCheck();" /><img onClick="xml_IDCheck()" style="cursor:hand" src="/imgs/btn_idcheck.gif" align="absmiddle">
       </p>
       <p></p>
      </form>
     </body>





    예제 샘플 :

    posted by Sunny's
    2009. 4. 16. 17:02 Ajax

    3. JSON의 데이터 타입(자료형)

    JSON의 데이터 타입은 다음과 같다.
    - string
    - number
    - boolean
    - null
    - array
    - object

    JSON Object의 각 프로퍼티 자료형은 "typeof"를 통해 확인이 가능하며, 각 자료형을 실제로 이용하는 예제를 통해 알아보기로 하자.

    아래의 각 예제들은 typeof를 통해 오브젝트 또는 프로퍼티의 자료형을 확인하고, 오브젝트의 프로퍼티 값을 확인하는 예제이다.


    ■ string

    string은 큰따옴표안에 둘러 싸인 zero 이상 Unicode 문자들의 조합이며, 쌍다옴표안에 감싸지며,backslash escape가 적용된다. 하나의 문자(character)도 하나의 문자열(character string)로서 표현된다. string은 C 또는 Java 문자열 처럼 매우 많이 비슷하다.
    <script language="JavaScript">
    <!--
      var obj1 = {
        "test" : "abc"
      };
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj1.test)" value="click">
    <input type="button" onclick="alert(obj1.test)" value="click">


    ■ number

    number는 8진수와 16진수 형식을 사용하지 않는것을 제외하면 C와 Java number 처럼 매우 많이 비슷하다.
    <script language="JavaScript">
    <!--
      var obj2 = {
        "test" : 123
      };
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj2.test)" value="click">
    <input type="button" onclick="alert(obj2.test)" value="click">


    ■ boolean

    boolean은 true/false의 값을 사용하며, C나 java의 boolean형과 비슷하다.
    <script language="JavaScript">
    <!--
      var obj3 = {
        "test" : true
      };
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj3.test)" value="click">
    <input type="button" onclick="alert(obj3.test)" value="click">


    ■ null

    null은 어떠한 형태를 담기 이전의 상태로, object로 취급받게 되며, 데이터가 할당되면 할당된 데이터의 타입에 따라 다시 구분되게 된다.
    <script language="JavaScript">
    <!--
      var obj4 = {
        "test" : null
      };
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj4.test)" value="click">
    <input type="button" onclick="alert(obj4.test)" value="click">
    <input type="button" onclick="obj4.test=false; alert(obj4.test)" value="click">


    ■ array

     array은 값들의 순서화된 collection 이다. array는 [ (left bracket)로 시작해서 ] (right bracket)로 끝내어 표현한다. , (comma)로 array의 값들을 구분한다.
    1) 1차원 배열
    <script language="JavaScript">
    <!--
      var obj5 = [
        "test"
      ]
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj5[0])" value="click">
    <input type="button" onclick="alert(obj5[0])" value="click">

    2) 2차원 배열
    <script language="JavaScript">
    <!--
      var obj6 = {
        "test" : [
          "ccc", "ddd"
        ]  
      }
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj6.test)" value="click">
    <input type="button" onclick="alert(obj6.test[0])" value="click">
    <input type="button" onclick="alert(obj6.test[1])" value="click">


    ■ object

     object는 name/value 쌍들의 비순서화된 SET이다. object는 { (좌 중괄호)로 시작하고 } (우 중괄호)로 끝내어 표현한다. 각 name 뒤에 : (colon)을 붙이고 , (comma)로 name/value 쌍들 간을 구분한다.
    <script language="JavaScript">
    <!--
      var obj7 = {
        "test" : {
          "name" : "k2club",
          "id" : 123
        }
      }
    //-->
    </script>

    <input type="button" onclick="alert(typeof obj7.test)" value="click">
    <input type="button" onclick="alert(obj7.test.name)" value="click">
    <input type="button" onclick="alert(obj6.test.id)" value="click">
    ※ object의 경우 array의 2차원 구조와 형태가 상당히 비슷하므로 주의하도록 하자.
    posted by Sunny's
    2009. 4. 16. 16:57 Ajax

    1. JSON(JavaScript Object Notation) 소개

    - JSON 공식 홈페이지 (http://www.JSON.org)
    - 한국어페이지 (http://www.json.org/json-ko.html)


    2. JSON의 기본

    기본적인 형태는 아래와 같이 사용이 가능하다.

    1) 프로퍼티 <-> 값
    var obj = {
       "프로퍼티 이름" : "값",
    }

    2) 메소드
    var obj = {
       "메소드 이름" : function() {alert('This is method')}
    }

    3) 메소드(인수)
    var obj = {
       "메소드 이름" : function(인수) {alert('This is method')}
    }

    이것만으로 오브젝트 obj를 만드는 것이 가능하여, obj.프로퍼티이름 으로 값을 얻어 낼 수 있어, obj.메소드이름() 으로 "This is method"라는 대화창을 표시한다.


    ■ 오브젝트

    아래와 같이 myJSONObject를 만들어보고 이를 Javascript를 이용해 확인해보자.
    <script language="JavaScript">
    <!--
      var myJSONObject = {
        "test" : "hello"
      }
    //-->
    </script>
    <form>
      <input type = "button" onclick="alert(typeof myJSONObject)" value="click">
    </form>


    ■ 프로퍼티

    <script language = "JavaScript">
    <!--
      var myJSONObject2 = {
        "test": "hello"
      }
    //-->
    </script>
    <form>
      <input type = "button" onclick = "alert( myJSONObject2 )" value = "click">
      <input type = "button" onclick = "alert( myJSONObject2.test )" value = "click">
      <input type = "button" onclick = "myJSONObject2.test = 'new test' ; alert(myJSONObject2.test )" value = "click">
    </form>

    1) alert(myJSONObject2)는 myJSONObject2가 object임을 보여준다.
    2) alert(myJSONObject2.test)는 myJSONObject2 오브젝트에서 test프로퍼티의 값 "hello"를 가져온다.
    3) myJSONObject2.test = 'new test' ;에서 test 프로퍼티의 값을 "new test"로 변경한다.
        alert(myJSONObject2.test)를 다시 수행하게되면 "hello"의 값이 "new test"로 변경되었음을 확인할 수 있다.

    위의 예에서는 프로퍼티가 한개인 경우를 테스트하여 보았다. 그렇다면 프로퍼티가 2개이상일 경우에는 어떻게 사용하는지 확인해보자.

    <script language="JavaScript">
    <!--
      var myJSONObject3 = {
        "test1": "hello1", "test2": "hello2", "test3":"hello3"
      }
    //-->
    </script>

    <form>
      <input type="button" onclick="alert(myJSONObject3.test1)" value="click">
      <input type="button" onclick="alert(myJSONObject3.test2)" value="click">
      <input type="button" onclick="alert(myJSONObject3.test3)" value="click">
    </form>

    부연 설명이 필요 없을정도로 깔끔하지 않은가?
    myJSONObject3의 각 프로퍼티인 "test1", "test2", "test3"를 각각 호출하면 각 프로퍼티의 값인 "hello1", "hello2", "hello3"를 꺼내오게된다.


    ■ 메소드

    <script language="JavaScript">
    <!--
      var myJSONObject4 = {
        "test1" : "function() { alert('This is method test1') }"
      }
    //-->
    </script>

    <form>
      <input type="button" onclick="eval('a=' + myJSONObject4.test1); a()" value="click">
    </form>
    ※ eval()함수는 변수를 javascript의 함수처럼 쓰는 명령어임.

    myJSONObject4의 메소드 test1을 실행하는 예를 보여주고 있다. 메소드 test1을 실행하면 "This is method test1"을 확인할 수 있다.


    ■ 메소드(인수)

    마지막으로, 메소드에 인수(파라미터)가 있는 경우는 어떻게 해야하는지 살펴보도록 하자.
    <script language="JavaScript">
    <!--
      var myJSONObject5 = {
        "test2" : "function(arg) { alert('This is argument : ' + arg) } "
      }
    //-->
    </script>

    <form>
      <input type="button" onclick="eval('var a=' + myJSONObject5.test2 + ''); a('hello');" value="click">
      <input type="button" onclick="eval('(' + myJSONObject5.test2+')(\'hello\')');" value="click">
    </form>
    </form>

    1) eval('var a=' + myJSONObject5.test2 + ''); a('hello');  
    2) eval('(' + myJSONObject5.test2+')(\'hello\')');

    두가지 모두 동일한 결과를 보여주고 있으므로 사용하기 편한 형태를 골라 사용하면 된다.
    posted by Sunny's
    2009. 4. 16. 16:12 Ajax

    JSON engine of VBScript based ASP server technology, served on it's deficiency of processing speciality. Also there have been like these projects put they had some deficiencies. For instance

    • find result late
    • difficult application
    • don't support full UNICODE
    • don't compatible with primitive datatypes
    • don't support to multi dimensional arrays
    • isn't extendable and iteratable

    This project solved all these matters.

    Hello World !

    sample

    <!--#include file="JSON_latest.asp"-->
    <%
    Dim member
    Set member = jsObject()

    member
    ("name") = "Tuğrul"
    member
    ("surname") = "Topuz"
    member
    ("message") = "Hello World"

    member
    .Flush
    %>

    output

    {"name":"Tu\u011Frul","surname":"Topuz","message":"Hello World"}

    SQL Queries

    sample

    <!--#include file="JSON_latest.asp"-->
    <!--#include file="JSON_UTIL_latest.asp"-->
    <%
    QueryToJSON(dbconn, "SELECT name, surname FROM members WHERE age < 30").Flush
    %>

    output

    [
       
    {
           
    "name":"ali",
           
    "surname":"osman"
       
    },
       
    {
           
    "name":"mahmut",
           
    "surname":"\u00E7\u0131nar"
       
    }
    ]

    Multi Dimensional Arrays

    sample

    <!--#include file="JSON_latest.asp"-->
    <%
    Dim a(1,1)

    a
    (0,0) = "zero - zero"
    a
    (0,1) = "zero - one"
    a
    (1,0) = "one - zero"
    a
    (1,1) = "one - one"

    Response.Write toJSON(a)
    %>

    output

    [["zero - zero","zero - one"],["one - zero","one - one"]]

    For more information you can reach


    출 처 : http://code.google.com/p/aspjson/

    Code license: MIT License
    Labels: asp, json, ajax, encode, vbscript, json

    How to join?
    Project owners:
      tugrultopuz
    posted by Sunny's
    2009. 4. 15. 09:16 Ajax

    JSON 은 써보면 써볼수록 유용한 것 같다. 간결하고 편하고 직관적이다. 어쨌든 JSON Text를 Object로 변환해야 할 때가 있다. 여기서 JSON Text라는 것은 형태는 JSON의 형태이지만 자바스크립트에서 이걸 Object가 아닌 그냥 텍스트로만 인식하고 있다는 것이다. 이걸 Object로 바꾸어야만 그안의 값을 불러다가 사용할 수 있다.

    가장 흔한 예가 Ajax를 사용할 경우이다. Ajax로 호출을 하고 결과값으로 받은 req.responseText로 JSON을 받았을 경우에는 그냥 Text이기 때문에 Object로 변환해 주어야 한다.

    { id:'Outsider', sex:'male' }

    Ajax에서 리턴받을 JSON의 형태가 위와 같이 되어 있을 경우에는

     
    1. var obj = eval("("+returnValue.responseText+")");   
    2. alert(obj.id);  // Outsider   

    위의 코드처럼 eval을 해주면 JSON 오브젝트로 변환할 수 있다.

    [ { id:'Outsider', sex:'male' },
      { id:'Zziuni', sex:'male' } ]

    JSON이 위의 형태처럼 배열로 되어 있을 경우에는

     
    1. var obj = eval(returnValue.responseText);   
    2. // -> { id:"Outsider", sex:"male" }   

    그냥 eval을 해주면 JSON 오브젝트로 변환할 수 있다.

    다만 이렇게 변환할 경우 eval()은 빠르기는 하지만 단순히 그안의 스트링을 그대로 실행시켜 주는 것이기 때문에 리턴값으로 자바스크립트 명령문이 온다면 그대로 실행시켜버리기 때문에 보안이슈가 발생할 수 있다. 

    이렇게 리턴받은 소스를 신뢰하기 어려울 때는 JSON.org 에서 제공하는 JSON parser을 사용해야 한다. JSON parser는 오직 JSON text만 받아들이고 다른 스크립트는 거부하고 eval()만큼이나 빠르다.

     
    1. var obj = JSON.parse(returnValue.responseText);   
    2. // -> { id:"Outsider", sex:"male" }   

    JSON.parse()의 목적대로 JSON 텍스트 외에는 거부해야하기 때문에 JSON문법을 정확히 지켜주지 않으면 SyntaxError 예외가 던져진다. 그렇기 때문에 키와 값을 모두 쌍따옴표(")로 묶어주는 문법을 정확하게 지켜주어야 한다. 아래처럼....

    { "id":"outsider", "sex":"male" }

    여기서 JSON.parse()를 사용하기 위해서는 Douglas Crockford 가 만든 json2.js 가 필요하다. json2.js는 더글라스 크록포드가 JSON의 편리한 사용을 위해 만든 JSON API의 새버전이다.(그래서 2가 붙어있다.) 이 API에는 2개의 메서드가 들어있는데 JSON.stringify()와 JSON.parse()이다. JSON.stringify()는 JSON.parse()와는 완전히 반대로 JSON 객체를 주면 JSON 텍스트로 만들어서 준다. 필요할때 갖다 쓰면 된다. (John Resig 이 이전버전보다 새버전의 API가 훨씬 좋다고 꼭 이걸 쓰란다.)


    출처 : http://blog.outsider.ne.kr/257
    posted by Sunny's
    2009. 4. 15. 09:10 Ajax

    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-교환 언어로 만들고 있다.

    (http://www.json.org/json-ko.html) 이곳에 들어가보면 json에 대해서 더 자세히 알 수 있습니다.

    json.org싸이트에서 주목해서 봐야 할 점은 json을 사용하기 위한 문법을 잘 익혀둬야 할것 같습니다.
    문법이 틀리다면 제대로 동작을 하지 않으니까요.(그다지 어렵지 않습니다. XML보다 훨씬 간단하더군요.)

    또한 JSON을 받을때 eval과 JSON.parse()에 대한 사용법에 대한 것은
    http://blog.outsider.ne.kr/257 - outsider님의 블로그를 참고 하시기 바랍니다.

    그리고 돌아다니다가 JSON을 확인 할 수 있는 ff용 확장 기능이 있어 소개해드립니다.
    JSONView  (FF확장기능)
    JSON예제파일

    posted by Sunny's
    prev 1 2 3 next