'3. Implementation/WEB'에 해당되는 글 6건

  1. 2015.03.17 Responsive Web
  2. 2011.07.23 [펌] jQuery로 Ajax 개발을 단순화 하기
  3. 2010.03.30 Making your web page compatible with Firefox
  4. 2010.01.23 Measuring Element Dimension and Location
  5. 2009.07.13 Character set, Character encoding, Code page, Unicode
  6. 2009.02.28 Using the XML HTTP Request object
2015. 3. 17. 02:03

Responsive Web

Here's good article :


http://helloworld.naver.com/helloworld/textyle/81480

2011. 7. 23. 15:20

[펌] jQuery로 Ajax 개발을 단순화 하기

원본: http://www.ibm.com/developerworks/kr/library/x-ajaxjquery.html
 

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_links는 external_links의 id를 가진 엘리먼트를 찾는다. 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() 함수가 필요하다. xmlhtmlscriptjson을 지정할 수 있고, 여러분이 바로 사용할 수 있도록 jQuery가 자동으로 콜백 함수에 대한 결과를 준비한다. 또한, beforeSenderrorsuccesscomplete 콜백을 지정하여 사용자에게 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 프로그래밍 방식을 진정으로 바꿔 놓았다.


참고자료

교육

제품 및 기술 얻기

토론

2010. 3. 30. 05:36

Making your web page compatible with Firefox

The following is a list of things to review so that a web page is compatible, not only with Firefox, but with any browser which implements the latest standards, including of course Mozilla derivates as Camino, Galeon, Epiphany, etc.

Some might say that making a page compatible requires double the effort in making it, and that is not worth the trouble since everybody uses explorer. In this article I want to show that this is not true. It's roughly the same effort to make a page that is compatible with Firefox as one that that is not.

This text does not intend to tell you how to make pages compatible with ancient browsers (as Netscape 4 or Explorer 4) That would certainly be a much larger task. This article aims to guide you about supporting browsers that are very similar in their support of things like dynamic HTML. It's not necessary to have a page for each kind of browser, it's better to share the code while taking into account the small differences. The details enumerated here will be used for browsers like Firefox, Mozilla, Netscape 6+, Konqueror, Opera, Apple's Safari, etc.. Some of the properties explained which are equivalent to those of Explorer don't belong to any standard, these cases will be noted.

Sripting. The great majority of the compatibility problems falls in this category, specially in "AJAX" applications. And they are not generally problems with the JavaScript language itself, but with the fact that the browsers represents the page in objects differently. A different API, sortof. This API is called the DOM (although in Microsoft docs you should search for DHTML instead).

Let's now see which are the most common problems...

http://www.reloco.com.ar/mozilla/compat.html

2010. 1. 23. 02:28

Measuring Element Dimension and Location

The following section is designed to help Web authors understand how to access the dimension and location of elements on the page through the Dynamic HTML (DHTML) Object Model.

Understanding Properties That Measure Element Dimension and Location

The diagrams illustrated in this document represent different DHTML Object Model properties for the same page. The sample page contains a div element that is relatively positioned on the page. Since the overflow attribute of the div has been set to scroll and it contains more content than can be displayed within its limited client area, scroll bars are displayed.



출처 : http://msdn.microsoft.com/en-us/library/ms533024%28VS.85%29.aspx

2009. 7. 13. 18:30

Character set, Character encoding, Code page, Unicode

1.     CharSet = Character Set

l  영문 표현 그대로 문자 집합이라는 의미입니다.

l  , 컴퓨터에서 문자를 표현하기 위해 각 문자를 정수 값에 대응시켜 놓은 체계를 말합니다. 숫자 코드가 컴퓨터 상에서 어떻게 표현되는 가는 정해지지 않은 상태라고 보면 됩니다.

l  예를 들어 한글 문자 집합에는 ’, ‘’, ‘’... 와 같은 문자들이 포함되어 있습니다. 이를 컴퓨터가 인식하기 위해서는 어떤 데이터이든 숫자로 표현해야 하기 때문에 '' 라는 문자는 0xac00라는 숫자값으로 매핑시켜 사용하도록 정의한 것을 charset이라고 하는 것입니다.

l  이러한 CharSet에는 언어 종류만큼 여러 개가 있을 수 있고, CharSet에 따라 표현하고자 하는 문자의 값과 대응되는 숫자의 값이 달라지게 됩니다. 따라서 문자를 주고 받을 때 서로간에 CharSet을 일치시켜야 할 필요가 있습니다. 그렇지 않으면 원래 의도된 내용이 아니 깨진 문자들을 보게 될 것이기 때문입니다.

l  웹 페이지 작성 시 content-type의 일부로 CharSet을 명시하는 것은 웹 브라우저에게 사용하는 CharSet을 알려주어 오해가 없도록 하기 위해서 입니다.

 

2.     Encoding

l  CharSet이 문자에 대해 정수값을 지정한 것이라면, encoding은 문자를 표현하는 정수값을 어떤 bit 배열로 표현할 것인지를 의미합니다. , encodingCharSet에서 더 나아가 컴퓨터 상에서 어떻게 표현되는 가까지 정해진 상태의 문자의 집합입니다. 예를 들어 같은 그림이라도 압축 방법에 따라 gif, png, bmp 등등의 파일 형식이 있듯이 CharSet과 encoding의 차이를 이해할 수 있습니다. 완성형 한글인 KSC-5601 CharSet은 UNIX에서는 EUC-KR이란 encoding으로 표현되고 윈도우즈에서는 cp949란 encoding으로 표현됩니다.

l  CharSet이 같다면 그 CharSet을 지원하는 어떤 encoding을 사용하든지 각 문자에 대응하는 논리적인 정수값은 동일하다고 할 수 있습니다. 그러나 실제로 기록되는 bit 배열은 encoding에 따라 달라질 수 있습니다. 이 경우, 제대로 데이터를 주고 받으려면 CharSet뿐만 아니라 encoding도 맞춰야 합니다.

 

3.     EUC & CodePage

l  EUC는 Extended Unix Code의 약자입니다. Unix 시스템이 전세계로 퍼져 나가면서 각국의 언어를 어떻게 표기할까를 고민하다가 각 나라별로 표준 CharSet을 개발하였는데, 이렇게 만들어진 것이 EUC입니다. 한국어는 EUC-KR(ksc5601+US-ASCII), 일본어는 EUC-JP으로 정의되어 있습니다.

l  CodePage는 Microsoft의 Windows 시스템에서 각 나라의 문자를 표기하기 위해 만든 CharSet입니다. 한국어는 949번을 할당 받아 cp949 혹은 codepage949로 소개되었습니다.

 

4.     Unicode

l  모든 글자 표현 체계를 하나로 통합하겠다는 취지로 만들어진 CharSet 입니다.

l  Unicode 자체는 어떤 특정한 바이트 형태를 지정하지는 않습니다. 그렇기 때문에 encoding이 필요하게 됩니다. Unicode != UTF-8 이며 Unicode encoding 중의 하나가 UTF-8은 될 수 있습니다.

l  UTF-8 ASCII로 표현 가능한 영문자는 1바이트로 표현을 하고 다른 문자들은 2~3바이트로 표현을 합니다. UTF-16 4바이트까지 사용합니다.

l  Windows 9x (Windows 95, 98, me) 계열은 Windows API를 표준적으로 ANSI 버전을 지원합니다. , UNICODE Windows API에서 직접 지원하지 않고 MBCS만을 직접 지원합니다. 이때, ANSI MBCS라고 생각해도 무관합니다.

l  ‘Windows NT (Windows NT, 2000, XP)계열은 Windows API ANSI 버전과 UNICODE 버전을 모두 지원합니다. ANSI API를 쓰는 경우에는 OS API를 다시 UNICODE 버전으로 변환해야 하므로 UNICODE 버전으로 만들어진 프로그램은 windows NT계열에서 약간의 속도 향상을 가져올 수 있다고 하겠습니다.

 

5.     UNIX에서의 Encoding

l  HTML : ISO-8859-1 ISO-10646

l  XML : UTF-8

l  웹 브라우저: 내부적으로 모두 유니코드로 처리를 함

l  HTTP/1.0 : ISO-8859-1

l  HTTP (URL,URI) : US-ASCII, %hexadecimal_code, JavaScript escape() 함수 사용

l  Java : 유니코드 2.0

l  직렬화된 Java Class : UTF-8

l  J2EE : ISO-8859-1

l  Oracle : UTF-8 (AL32UTF8), 한국에서는 KSC5601 (KO16KSC5601)



출처 : http://blogs.technet.com/hjjeon/archive/2009/03/13/character-set-character-encoding-code-page-unicode.aspx
2009. 2. 28. 04:42

Using the XML HTTP Request object

Internet Explorer on Windows, Safari on Mac OS-X, Mozilla on all platforms, Konqueror in KDE, IceBrowser on Java, and Opera on all platforms including Symbian provide a method for client side javascript to make HTTP requests. From the humble begins as an oddly named object with few admirers, it's blossomed to be the core technology in something called AJAX [1].

The Object makes many things easier and neater than they other would be, and introduces some things that were otherwise impossible such as HEAD requests to see when a resource was last modified, or to see if it even exists. It makes your scripting options more flexible allowing for POST requests without having the page change, and opens up the possibility of using PUT, DELETE etc. These methods are increasingly used to provide richer Web Applications like G-Mail that use lower bandwidth and offer snappier user interaction.

Why XML HTTP Request object?

Whilst the object is called the XML HTTP Request object it is not limited to being used with XML, it can request or send any type of document, although dealing with binary streams can be problematical in javascript.

Creating the object

In Internet Explorer, you create the object using new ActiveXObject("Msxml2.XMLHTTP") or new ActiveXObject("Microsoft.XMLHTTP") depending on the version of MSXML installed. In Mozilla and Safari (and likely in future UA's that support it) you use new XMLHttpRequest() IceBrowser uses yet another method the window.createRequest() method.

This means that you need to show different script to different browsers, as what works in one, will error in another. The script below does this, and if it's not supported, the variable is set to false to allow for appropriate error messages and recovery with degrading to more normal HTTP transaction methods when the object isn't available. This degradation is important, even in IE the objects can often be blocked by slightly raised security settings (popular due to the commonly exploited holes of course). Where possible degrade, some approaches are talked about below, if you really can't, I'd recommend providing an alternative page aswell. GMail for example has said they'll be providing a less demanding version in the future, hopefully with no javascript at all, full degradation.

var xmlhttp=false;

/*@cc_on @*/

/*@if (@_jscript_version >= 5)

// JScript gives us Conditional compilation, we can cope with old IE versions.

// and security blocked creation of the objects.

 try {

  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

 } catch (e) {

  try {

   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

  } catch (E) {

   xmlhttp = false;

  }

 }

@end @*/

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {

       try {

              xmlhttp = new XMLHttpRequest();

       } catch (e) {

              xmlhttp=false;

       }

}

if (!xmlhttp && window.createRequest) {

       try {

              xmlhttp = window.createRequest();

       } catch (e) {

              xmlhttp=false;

       }

}

How do I make a request?

Making a HTTP request is very simple. You tell the XML HTTP request object what sort of HTTP request you want to make and which url you want to request. Provide a function to be called when as the request is being made, and finally what, (if any) information you want sent along in the body of the request.

The following script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete, it displays the responseText to the user with an alert.

 xmlhttp.open("GET", "test.txt",true);

 xmlhttp.onreadystatechange=function() {

  if (xmlhttp.readyState==4) {

   alert(xmlhttp.responseText)

  }

 }

 xmlhttp.send(null)

Making a HEAD request

With a HEAD request, a server will only return the headers of a resource, rather than the resource itself, this means you can find out the Content-Type or Last-Modified of a document, without downloading it itself.

A typical HEAD request might return something like this:

HTTP/1.1 200 OK

Server: Microsoft-IIS/4.0

Cache-Control: max-age=172800

Expires: Sat, 06 Apr 2002 11:34:01 GMT

Date: Thu, 04 Apr 2002 11:34:01 GMT

Content-Type: text/html

Accept-Ranges: bytes

Last-Modified: Thu, 14 Mar 2002 12:06:30 GMT

ETag: "0a7ccac50cbc11:1aad"

Content-Length: 52282

To make a HEAD request, you simply replace the first parameter with HEAD, and then extract the headers, either using getAllResponseHeaders or getResponseHeader("Name") to get an individual one.

 xmlhttp.open("HEAD", "/faq/index.html",true);

 xmlhttp.onreadystatechange=function() {

  if (xmlhttp.readyState==4) {

   alert(xmlhttp.getAllResponseHeaders())

  }

 }

 xmlhttp.send(null)

Using HEAD requests, to find the Last-Modified of another file.

One use of HEAD requests, is to find out when a url was modified, extending the previous example, you get something like this:

 xmlhttp.open("HEAD", "/faq/index.html",true);

 xmlhttp.onreadystatechange=function() {

  if (xmlhttp.readyState==4) {

   alert("File was last modified on - "+

    xmlhttp.getResponseHeader("Last-Modified"))

  }

 }

 xmlhttp.send(null)

To format the date differently, or use something other than alert, the javascript FAQ will tell you more.

Does a url exist?

Another simple use is finding if a url exists, in HTTP there are various status codes returned by both HEAD and GET requests, 200 means success, 404 means failure, and the others mean other things. See HTTP status codes for a full explanation. using the status property of the xmlhttp object provides you this status

 xmlhttp.open("HEAD", "/faq/index.html",true);

 xmlhttp.onreadystatechange=function() {

  if (xmlhttp.readyState==4) {

   if (xmlhttp.status==200) alert("URL Exists!")

    else if (xmlhttp.status==404) alert("URL doesn't exist!")

     else alert("Status is "+xmlhttp.status)

  }

 }

 xmlhttp.send(null)

Calling a server-side Script without refreshing the page

Forms are the way to "call" serverside scripts in HTML, they force the page reload, and this is often not very user friendly. Using the HTTP Request, you can call the script without refreshing the page, and still have the form "fallback" to working when the XML HTTP Request Object is not available.

<%

 a=+(Request.QueryString('a')+'')

 b=+(Request.QueryString('b')+'')

 if (isNaN(a) || isNaN(b)) {a='';b='';total='' }

  else {

   total=a+b

  }

 acc=Request.ServerVariables('HTTP_ACCEPT')+''

 if (acc.indexOf('message/x-jl-formresult')!=-1) {

  Response.Write(total)

 } else {

%>

<script src="xmlhttp.js" type="text/javascript"></script>

<script>

 function calc() {

  frm=document.forms[0]

  url="add.1?a="+frm.elements['a'].value+"&b="+frm.elements['b'].value

  xmlhttp.open("GET",url,true);

  xmlhttp.onreadystatechange=function() {

   if (xmlhttp.readyState==4) {

    document.forms[0].elements['total'].value=xmlhttp.responseText

   }

  }

 xmlhttp.setRequestHeader('Accept','message/x-jl-formresult')

 xmlhttp.send()

 return false

}

</script>

<form action="add.1" method="get" onsubmit="return calc()">

<input type=text name=a value="<%=a%>"> + <input type=text name=b value="<%=b%>">

 = <input type=text name=total value="<%=total%>">

<input type=submit value="Calculate">

</form>

<%

}

%>

 

The example above uses JScript in ASP as the server side language, the HTTP ACCEPT header is used to tell the server which response to send back - either the full page or just the result. The HTTP ACCEPT header is used to tell servers what mime-types the client will accept, normally it says things like text/html etc. Here though we tell it we only accept "message/x-jl-formresult", so the server knows it is our client (or another client, who knows about "message/x-jl-formresult") making the request.

Other methods of identifying what to return may be appropriate depending on the type of data you send to the server, or you could simply use different urls for the form submission and xmlhttp request, whatever you do, remember to have sensible fallback to the non-xml http request browsers where possible.

Using JSON as the transfer language

Whilst XML can be used to encode the information you retrieve with the object and it will be available in the responseXML property, however xml is less well supported, some browsers require that the content type of the resource is one of only 2 possible XML mime-types text/xml or application/xml for the property to be populated, and there are always the normal well formness problems you always get with XML. JSON is a good alternative, it's fast to parse, and much, much faster to access in script.

I use JSON in the Flight Routeplanner to look up information on airports, an Example with London Heathrow, you can easily parse the returned JSON into a script object using the new Function constructor, it checks the status as the script returns 404 if it fails to find an airport with that iata code.

 xmlhttp.open("GET","/routeplanner/airport.1?LHR",true);

 xmlhttp.onreadystatechange=function() {

  if (xmlhttp.readyState==4) {

   if (xmlhttp.status!=404) {

    var local=new Function("return "+xmlhttp.responseText)();

    alert("Code - Name\n"+local[0].id+' - '+local[0].name);

   } else {

    alert("Airport not found");

   }

  }

 }

 xmlhttp.send(null);

Using XMLHTTP with GOOGLE's SOAP API

Google provides a SOAP interface to it's database. You need to register for a key that lets you make 1000 a day, to make a request. You then need to parse the returned XML.

 search="Word"

 xmlhttp.open("POST", "http://api.google.com/search/beta2",true);

 xmlhttp.onreadystatechange=function() {

  if (xmlhttp.readyState==4) {

   alert(xmlhttp.responseText)

  }

 }

 xmlhttp.setRequestHeader("Man", "POST http://api.google.com/search/beta2 HTTP/1.1")

 xmlhttp.setRequestHeader("MessageType", "CALL")

 xmlhttp.setRequestHeader("Content-Type", "text/xml")

 

 xmlhttp.send("<?xml version='1.0' encoding='UTF-8'?>"+"\n\n"+"<SOAP-ENV:Envelope"+

      ' xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"'+

      ' xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"'+

      ' xmlns:xsd="http://www.w3.org/1999/XMLSchema">'+

      '<SOAP-ENV:Body><ns1:doGoogleSearch'+

      ' xmlns:ns1="urn:GoogleSearch"'+

      ' SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+

      '<key xsi:type="xsd:string">GOOGLEKEY</key> <q'+

      ' xsi:type="xsd:string">'+search+'</q> <start'+

      ' xsi:type="xsd:int">0</start> <maxResults'+

      ' xsi:type="xsd:int">10</maxResults> <filter'+

      ' xsi:type="xsd:boolean">true</filter> <restrict'+

      ' xsi:type="xsd:string"></restrict> <safeSearch'+

      ' xsi:type="xsd:boolean">false</safeSearch> <lr'+

      ' xsi:type="xsd:string"></lr> <ie'+

      ' xsi:type="xsd:string">latin1</ie> <oe'+

      ' xsi:type="xsd:string">latin1</oe>'+

      '</ns1:doGoogleSearch>'+

    '</SOAP-ENV:Body></SOAP-ENV:Envelope>')

 

Google is using a SOAP interface, many people think SOAP has some serious issues worth considering. REST is probably a better model as it works with the current web framework, proxies, caches etc. So whilst we can use the XML HTTP Request object to talk soap, it's probably best not to unless you have no control over what's happening on the server end. (Thanks to Dan Schmierer for pointing out an error in my script.)

By default the object can only call back to the same server, in a reduced security environment (accessed from file:// say) IE can access any domain, Mozilla can also do that if you request and are granted the appropriate permissions see "a google thread I can't get to offline!"

Nearby...

[1] Actually a lot of the "AJAX" applications make little use of this object, using the older and often more flexible IFRAME remote scripting methods, but they could've been using this object, and AJAX should be thought of more as a concept of the kind of applications that can be created with the object.

 

From : http://www.jibbering.com/2002/4/httprequest.html