자바 스크립트 내에서 XML 노드 Value값를 가져오는 방법이다.
처음에는 아래와 같이 jQuery를 이용하여 처리하고자 진행하였다.
var xml = '';
$(xml).find("id").each(function () {
   var id = $(this).find("id").text();
});
그러나 XML 노드에 CDATA 타입으로 지정되어 있으면 항상 ''로 리턴되어 사용할 수 없었다.
좀 더 테스트 해보니, Dom Parser 처리 후 조회해보니 값을 제대로 가져온다.ㅎ
var xml = '';

var xmlDoc;
if (window.ActiveXObject) {
    // IE일 경우
    xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
    xmlDoc.async = false;
    xmlDoc.loadXML(xml);
}
else if (window.XMLHttpRequest) {
    //Firefox, Netscape일 경우
    var xmlParser = new DOMParser();
    xmlDoc = xmlParser.parseFromString(xml, 'text/xml');
}
else {
    xmlDoc = null;
}

if (xmlDoc != null) {
    // #1. jQuery 방식 
    $(xmlDoc).find("To").each(function () {
        var id = $(this).find("dn").text();
    });

    // #2. Script 방식
    var nodes = xmlDoc.selectNodes("person/to");
    for (i = 0; i < nodes.length; i++) {
        var id = nodes[i].selectSingleNode("id").text;
    }
}

WebService 내 DataTable 이용하여 로직 구현 후, JQuery로 데이터 가져오는 방법
페이지 코드
 

JQuery Demo Page



이름 나이
WebService 코드
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace TEST.WS
{
    /// 
    /// UserInfoWS의 요약 설명입니다.
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다. 
    [System.Web.Script.Services.ScriptService]
    public class UserInfoWS : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetUserInfo(string id)
        {
            DataTable dtUserInfo = new DataTable("UserInfo");

            dtUserInfo.Columns.Add("FirstName", typeof(string));
            dtUserInfo.Columns.Add("LastName", typeof(string));
            dtUserInfo.Columns.Add("Age", typeof(string));
            dtUserInfo.Columns.Add("ID", typeof(string));

            DataRow drUserInfo = dtUserInfo.NewRow();
            drUserInfo["FirstName"] = "길동";
            drUserInfo["LastName"] = "홍";
            drUserInfo["Age"] = "29";
            drUserInfo["ID"] = id;
            dtUserInfo.Rows.Add(drUserInfo);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List userInfos = new List();
            UserInfo userInfo = null;
            foreach (DataRow dr in dtUserInfo.Rows)
            {
                userInfo = new UserInfo();
                userInfo.FirstName = dr["FirstName"].ToString();
                userInfo.LastName = dr["LastName"].ToString();
                userInfo.Age = dr["Age"].ToString();
                userInfo.ID = dr["ID"].ToString();

                userInfos.Add(userInfo);
            }

            return serializer.Serialize(userInfos);
        }

        public class UserInfo
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Age { get; set; }
            public string ID { get; set; }
        }
    }
}
여기서 주의 할 점..

  1. WebMethod 내 JavaScriptSerializer 클래스를 통하여 DataTable 개체를 JSON 문자열로 변환하여 String으로 리턴하여야 함.
    -  
      Object 타입의 개체를 넘겨주어야 하므로, 위 소스에서는 별도의 클래스를 정의하여 개체로 넘김.
  2. 위 JSON 문자열로 처리 했다고 해서.. JQuery ajax 내에서 return.d 로만 처리하면 속성값을 찾지 못함.

    success: function (result) {
          data = $.parseJSON(result.d);
          
    $.each(data, function (i, item) {
                   //위처럼 선언 안하고, item.FirstName 속성 값을 가져오지 못함.
           }
    }; 

8.1 Ajax 간략히 살펴보기

8.1.1 XHR 인스턴스 생성하기

8.1.2 요청 보내기

8.1.3 진행 상황 추적하기

8.1.4 응답 얻기

  • Ajax를 사용하는 개발자가 다뤄야할 고통
    • XHR 객체를 인스턴스화 하는데 브라우저에 종속적 코드 필요
    • 준비 핸들러는 필요없는 상태 변화를 걸러내야 한다.
    • 준비 핸들러는 XHR인스턴스를 호출하는 참조를 자동으로 얻지 못한다.
    • 응답결과는 형태에 따라 다양한 방법으로 다뤄야 한다.

8.2 엘리먼트에 콘텐츠 로드하기

  • Ajax를 사용하는 가장 빈번한 상황은 서버에서 콘텐츠를 가져와서 원하는 DOM 위치에 삽입하는 것이다.
  • 콘텐츠는 대상 컨테이너의 자식이 되는 HTML코드이거나 대상엘리먼트의 콘텐츠가 되는 보통 텍스트다.
  • $('#someContainer).load('/serverResource'); - 간단하다.

8.2.1 jQuery로 콘텐츠 로드하기

  • load(url, parameters, callback) - parameters 매개변수가 요청 매개변수로 제공되면 POST HTTP 메서드를 사용하여 요청을 만들고, 그렇지 않으면 GET 메서드로 요청을 만든다. (GET URL에 URI인코딩 형태의 쿼리문자열 추가)
  • $('.injectMe').load('/someResource #div'); - 응답 엘리먼트에서 오직 <div>엘리먼트만 삽입한다.
  • serialize() - 폼 컨트롤에서 요청 매개변수를 가져와 쿼리 문자열을 만들어줌(선택안된 체크박스 라디오버튼 드롭다운, 비활성화된 컨트롤과 같은 엘리먼트는 제외)
  • serializeArray() - 자바스크립트 배열형태로 폼데이터를 반환. 폼 컨트롤 이름과 값을 name 프로퍼티와 value 프로퍼티로 가짐

8.2.2 목록 데이터 동적으로 로드하기

  • $(function(){

             $('#styleDropdown')

                  .change(function(){   // 스타일 드롭다운을 감싸고 변경 핸들러를 바인딩한다.

                     var styleValue = $(this).val();

                     $('#detailsDisplay').load(

                            'getDetails.jsp',     // 선택된 스타일 데이터를 로드한다.

                            { style : styleValue } // GET 패러메터

                     );

                  })

                  .change();               // 변경 핸들러를 실행한다.

             });

8.3 GET과 POST 요청 만들기

  • GET은 멱등 요청이며 캐시에 적합하다.
  • POST는 데이터 전송에 주로 쓴다.

8.3.1 jQuery를 사용하여 데이터 얻기

  • $.get(url, parameters, callback) - 명시된 URL을 사용하여 GET요청을 전송
  • $.get( 'reflectData.jsp', {a:1, b:2, c:3}, function(data) {alert(data);} );

8.3.2 JSON 데이터 얻기

  • XML이 데이터 전송기법으로 적당하지 않을때 사용
  • $.getJSON(url, parameters, callback)

8.3.3 POST 요청 만들기

  • $.post(url, parameters, callback)

8.4 Ajax 요청 직접 제어하기

8.4.1 Ajax 요청 직접 설정하고 생성하기

8.4.2 요청에 기본값 설정하기

8.4.3 전역함수

 

 

7.1 확장을 사용하는 이유

  • 사이트 전체에 일관된 코드 스타일을 유지하는 데 도움을 줌
  • jQuery의 강력한 기능을 상속받아 사용 가능

7.2 jQuery 플러그인 제작 지침

7.2.1 필드와 함수 이름 짓기

  • 플러그인 개발시에 파일이름이 다른 파일과 충돌하지 않도록 만드는 방법
    • 접두어로 jquery.를 사용한다.
    • 이어서 플러그인 이름을 적는다.
    • .js로 파일 이름을 끝맺는다.
  • jquery.fred.js
  • http://docs.jquery.com/Plugins 페이지의 플러그인 목록을 살펴보는 것도 좋다.

7.2.2 $를 경계하라

  • 별칭 jQuery를 사용하는 방법도 있으나 $쪽이 훨신 편리하다.

7.2.3 복잡한 매개변수 목록을 단순하게 만들기

  • function complex(p1, p2, p3, p4, p5, p6, p7) {  - 매개변수가 많음
  • complex(valueA, null,null,null,null,null, valueB); - null 입력이 많음
  • complex(valueA, {p7:valueB}); - options hash를 이용하는 방법
  • complex(valueA, {p3:vlaueC, p4:valueD})); - 이런 방법도

7.3 사용자 정의 유틸리티 함수 작성하기

  • $.say = function(what) { alert('I say ' + what); }

7.3.1 데이터를 조작하는 유틸리티 함수 만들기

  • $.toFixedWidth(value, length, fill) - 전달된 값을 고정폭 필드로 채우는 함수를 만들어 보자
  • (function($){

   $.toFixedWidth = function(value, length, fill) {

        var result = value.toString();

        if(!fill) fill = '0;;

        var padding = length - result.length;

        if(padding < 0) {

             result = result.substr(-padding);

        }

        else {

             for(var n = 0; n < padding; n++)

                 result = fill + result;

        }

        return result;

   };

})(jQuery); - 이렇게 구현한다.

7.3.2 날짜 형식기 만들기

7.4 새로운 확장 메서드 추가하기

  • 확장 메서드를 추가하여 강력함을 필요한 만큼 확장할 수 있다.

7.4.1 확장메서드에 여러동작 적용하기

  • 두가지 이상 되는 기능을 수행하는 새로운 플러그인 메서드 개발

7.4.2. 확장메서드에서 상태 유지하기


6.1 jQuery 플래그 사용하기

  • $.browser, $.boxModel, $.styleFloat

6.1.1 사용자 에이전트 탐지하기

  • 브라우저 탐지가 해로운 이유 - 브라우저 탐지는 '증오스럽다'. 브라우저 탐지는 선택할 여지가 없을 때만 사용하는 기술이다. IE, firefox, opera, safari 등등 , 지원하지 않는 브라우저는 에러 발생 ,거대 중첩 조건문에 의해 확장성 떨어짐
  • $.browser - 에이전트가 속한 브라우저 종류를 찾으려고 사용하는 플래그 집합을 정의한다. msie, mozilla, safari, opera, version
  • $.browser.msie ? 2 : select.option[2] - 브라우저를 탐지하여 처리

6.1.2 박스 모델 확인하기

  • W3C 박스 모델은 패딩과 테두리 엘리먼트의 크기를 넓이에서 제외하지만 IE에서는 포함한다.
  • $.boxModel - W3C 표준 박스 모델이면 true, IE 박스모델은 false

6.1.3 정확한 float 스타일 탐지하기

  • element.style[$.styleFloat] = 'left';
  • $.styleFloat 플래그 값은 IE에서 styleFloat이며 다른 브라우저에서는 cssFloat이다.
  • 이 플래그를 일반적으로 직접 사용하는 일이 없다.

6.2 다른 라이브러리와 jQuery 함께 사용하기

  • $.noConflict() - 다른 라이브러리가 $를 사용하면 그 라이브러리에서 이변수를 사용할 수 있도록 만들어 주는 유틸리티 함수

6.3 자바스크립트 객체와 컬랙션 조작하기

6.3.1 문자열 다듬기

  • $.trim(value) - 앞뒤 공백 제거(폼피드, 개행, 리턴, 탭, 수직문자 등 포함)

6.3.2 프로퍼티와 컬렉션 순회하기

  • for-in루프 는 문법이 불필요하게 장황하고 복잡해짐
  • $.each(container, callback) - container는 순회할 아이템을 가진 배열 혹은 프로퍼티를 가진 객체, callback함수의 첫번째 매개변수는 배열의 인덱스 이거나 객체 프로퍼티의 이름이다.
  • var anArray = ['하나','둘','셋'];

$.each(anArray, function(n, value){

    // 여기서 작업한다.

});

  • $var anArray = {하나:1, 둘:2, 셋:3};

$.each(anObject, function(name, value){

    // 여기서 작업한다.

});

6.3.3 배열 필터링하기

  • 많은 양의 데이터를 다루는 애플리케이션에서 특정조건에 일치하는 엘리먼트를 찾으려면 빈번하게 배열을 순회하여야한다.
  • 특정경계에 속하거나 속하지 않는 아이템 혹은 특정 패턴에 일치하는 아이템을 찾기위해 필터링 작업을 한다.
  • $.grep(array, callback, invert) - 전달된 배열의 엘리먼트마다 콜백함수를 호출하면서 순회한다. invert 매개변수를 생략하거나 false이면 콜백의 값이 true일 경우 값이 수집된다. invert가 true라면 콜백의 값이 false일 때 값이 수집된다. 원본 배열은 변경되지 않는다.
  • var bigNumbers = $.grep(originalArray, function(value){

return value > 100;

}); - 배열중 100보다 큰 값으로 필터링

6.3.4 배열 변환하기

  • 데이터가 항상 필요한 형태로만 존재하지는 않는다. 데이터 중심 웨에플리케이션에서 자주 사용하는 주요 동작으로 값의 집합을 다른 집합으로 변환하는 연산이 있다.
  • $.map(array, callback) - 전달된 배열의 아이템마다 콜백함수를 호출하면서 순회하며 함수호출로 반환된 값은 새로운 배열로 수집된다.
  • var oneBased = $.map([0,1,2,3,4], function(value){return value+1;}); - 0 기반 인덱스에서 1기반 인덱스로 변경한다.
  • var oneBased = $.map([0,1,2,3,4], 'a+1'); - 위와 같은식, 간단하게 만드는 표현식 형태의 문자열을 전달 할 수 있다. a라는 매개변수를 값으로 전달 받았다.
  • var strings = ['1', '2', '3', '4', 'S', '6'];  // 5가 아니라 S

var values = $.map(strings, function(value){

var result = new Number(value);

return isNaN(result) ? null : result; // 숫자로 성곡적으로 변환했는지 점검 (자바스크립트 isNaN() 메서드), 실패시 null 반환

});

  • var characters = $.map(['this', 'that', 'other thing'],

function(value) { return value.split(''); }

);

==> ['t','h','i','s','t','h','a','t','o','t','h','e','r ',' ','t','h','i','n','g'] 합쳐서 분해 됨

6.3.5 자바스크립트 배열 재미있게 사용하기

  • $.inArray(value, array) - 전달된 값이 처음 나타나는 위치 인덱스 반환, value 배열에서 찾으려는 값, 찾을 대상 배열 , 찾지 못하면 -1 반환
  • var index = $.inArray(2,[1,2,3,4,5]);
  • $.makeArray(object) - 유사배열 객체를 자바스크립트 배열로 변환
  • $.unique(array) - DOM 엘리먼트의 배열이 주어지면, 원본 배열에서 고유한 엘리먼트로만 구성된 배열 반환.

6.3.6 객체 확장하기

  • $.extend(target, source1, source2, ...sourceN) - target에 전달될 객체를 함께 전달된 나머지 객체의 프로퍼티를 사용하여 확장한다. 같은 객체가 있을 때  뒤에 나오는 객체가 앞보다 우선함.

6.4 동적으로 스크립트 로드하기


5.1 엘리먼트를 나타내고 감추기

5.1.1 접을 수 있는 리스트 구현하기

  • show(), hide()

5.1.2 엘리먼트의 표시 상태 바꾸기

  • toggle()

5.2 엘리먼트 표시상태를 애니메이션으로 표현하기

5.2.1 엘리먼트를 점진적으로 보이고 감추기

  • hide(speed, callback) - 매개변수 없으면 display 스타일 프로퍼티 값이 즉시 none으로 설정, speed 는 1/1000초 설정, 또는 slow, normal, fast
  • show(speed, callback) - jQuery를 이용해 감췄다면 이전 값으로 설정한다. 그렇지 않으면 block으로 설정
  • toggle(speed, callback) - 감춰진 경우는 show()를 수행, 드러난 경우는 hide()를 수행

5.2.2 엘리먼트 페이드인 / 페이드 아웃/ 페이드 투하기

  • fadeOut(speed, callback) - 불투명도를 0%로 줄여가면서 화면에서 제거
  • fadeIn(speed, callback)
  • fadeTo(speed, opacity, callback) - 확장엘리먼트의 불투명도를 현재의 설정 값에서 opacity 매개변수 값으로 설정 한다. (0.0~1.0) 화면에서 제거하지는 않는다.

5.2.3 슬라이드 효과를 사용하여 엘리먼트를 나타내고 감추기

  • slideDown(speed, callback) - 감춰진 모든 일치하는 엘리먼트가 높이 값이 증가하면서 나타난다. (펼쳐지는...)
  • slideUp(speed, callback) - 드러나 있는 모든 일치하는 엘리먼트가 점차적으로 높이 값이 감소하면서 화면에서 제거된다.
  • slideToggle(speed, callback) - 감춰진 확장엘리먼트는 slideDown()을, 드러나 있는 확장 엘리먼트에는 slideUp()을 수행한다.

5.2.4 애니메이션 멈추기

  • stop() - 확장 집합에 있는 엘리먼트에 현재 진행하는 에니메이션을 중지한다.

5.3 사용자 정의 애니메이션 생성하기

  • 자신만의 애니메이션을 만들 수 있다.
  • animate(properties, duration, easing, callback)
  • animate(properties, options)

5.3.1 사용자 정의 스케일 애니메이션

  • $('.animateMe').each(function(){

    $(this).animate(

        {

            widh: $(this).width() * 2,

            height: $(this).height() * 2

        },

        2000

   );

});

5.3.2 사용자 정의 드롭 애니메이션

  • $('.animateMe').each(function(){

               $(this)

                  .css('position', 'relative')

                  .animate(

                       {

                            opacity: 0,

                            top: $(window).height() - $(this).height() - $(this).position().top

                        },

                        'slow',

                        function(){ $(this).hide(); });

           }); - 화면에서 떨어지는 효과

 

5.3.3 사용자 정의 퍼프 애니메이션

  • 담배 연기 같이 공중에 퍼지는 것처럼 보이게 하려고 한다.
  • $('.animateMe').each(function(){

    var position = $(this).position();

    $(this)

        .css({position:'absolute', top:position.top, left:position.left})

        .animate(

              {

                   opacity: 'hide',

                   width: $(this).width() * 5,

                   height: $(this).height() * 5,

                   top: position.top - ($(this).height() * 5 / 2 ),

                   left: position.left - ($(this).width() * 5 / 2)

              },

              'normal');

});

                    

 

jQuery in Action 정리 4장 - 이벤트 -모든것의 시작 | jQuery
전체공개 2010.12.29 14:40

4.1 브라우저 이벤트 모델 이해하기

4.1.1 DOM 레벨 0 이벤트 모델

  • 어트리뷰트 방식으로 DOMM 레벨 0 이벤트 헨들러를 선언하는 방법은 1.2 절에서 설명한 튀지않는 자바스크립트 원칙을 위반한다.
  • Event 인스턴스의 프로퍼티는 발생한 이벤트에 관한 많은 정보를 제공한다. 엘리먼트 마우스이벤트 좌표, 키보드 이벤트의 키 정보 등
  • 이벤트 버블링. 먼저 대상이 되는 엘리먼트에게 이를 전달한 뒤, 조상 엘리먼트에게 순서대로 이벤트를 전달하는 과정. 이걸 멈출 수 있나?
  • 표준 호환 브라우져에서는 stopPropagation()메서드, IE에서는 cancleBubble프로퍼티

4.1.2. DOM 레벨 2 이벤트 모델

  • 프로퍼티에 저장하는 레벨 0 방식은 두가지 동작 처리 안됨
  • 레벨 2에서는 하나이상 할당하도록 설계
  • addEventListener(eventType, listener, useCapture) 메서드를 사용
  • 이벤트 버블링. 루트에서 대상 엘리먼트로 전파(캡쳐단계), 다시 대상엘리먼트에서 루트로 전파(버블단계)
  • useCapture 매개변수를 false로 설정하면 버블 헨들러, true로 하면 캡쳐 헨들러
  • ie는 캡쳐단계 지원 안함

4.1.3 인터넷 익스플로러 이벤트 모델

  • ie 7에서도 DOM 레벨 2를 지원하지 않음
  • ie는 attachEvent(eventName, handler)라는 비슷한 것을 지원
  • jQuery를 통해 이런 브라우저간 차이를 해결

4.2 jQuery 이벤트 모델

  • 이벤트 핸들러를 할당할 수 있는 통합 메서드 제공
  • 엘리먼트 이벤트 타입마다 여러 헨들러 할당 가능
  • click, mouseover 같은 표준 이벤트 타입 사용
  • 핸들러 매개변수를 써서 Event 인스턴스를 사용
  • 자주 사용하는 Event 인스턴스의 프로퍼티들에 일관된 이름을 사용
  • 이벤트 해제와 기본행동을 막는 통합메서드 제공
  • 캡쳐단계는 지원하지 않음

4.2.1 jQuery를 사용해 이벤트 핸들러 바인딩하기

  • $('img').bind('click', function(event){alert('안녕!');});
  • eventTypeName - blur, change, click, dblclick, error, focus, keydown, keypress, keyup, load, mousedown, mousemove, mouseout, mouseover, mouseup, resize, scroll, select, submit, unload
  • .one() - 한번 실행 뒤 자동 삭제되는 핸들러

4.2.2 이벤트 핸들러 제거하기

  • .unbind(eventType, listenner)
  • .unbind(event)

4.2.3 Event 인스턴스

4.2.4 이벤트 전파 제어하기

4.2.5 이벤트 핸들러 호출하기

  • .trigger(eventType) - 일치된 엘리먼트에 대하여 전달된 이벤트 타입에 해당하는 이벤트 핸들러를 모두 실행한다. 단, 이벤트를 발생 시키지 않으며 전파 안됨
  • .blur(), .click(), .focus(), .select(), .submit() 등을 지원

4.2.6 그 외 이벤트 관련 커맨드

  • 리스너 토글하기 - toggle(listenerOdd, listenerEven) 번갈아 가면서 실행될 클릭 이벤트 핸들러 한쌍을 할당
  • 엘리먼트 위에서 맴돌기 - hover(overListener, outListener) 자식 엘리먼트로 이동은 무시됨
  • $('#outer2').hover(report, report);

4.3 이벤트 사용하기

  • HTML에는 화면을 꾸미는 정보는 담지 않는다. CSS로 정의
  • HTML에는 스크리브로 포함하지 않는다 (튀지않는 자바스크립트원칙)

     


3.1 엘리먼트 프로퍼티와 어트리뷰트 조작하기

3.1.1 엘리먼트 프로퍼티 조작하기

  • $('img').each(function(n){ this.alert='아이디가 '+this.id+'인 image['+n+']이다.'; }); - 0 부터 시작하는 index n을 매개변수로 받는다.
  • var allAlts = new Array();

$('img').each(function(){ allAlts.push(this.alt); });  - 모든 alt 배열을 얻음

3.1.2 어트리뷰트 값 가져오기

  • $("#myImage").attr("custom") - costom 어트리뷰트의 값
  • 브라져에 따라 다른 프로퍼티명 때문에 발생하는 귀찮은 문제를 해결해 준다. (ex className 등)

3.1.3 어트리뷰트 값 설정하기

  • $('*').attr('title', function(index) {

return '나는 ' + index + '번 엘리먼트이고 내 이름은 ' + (this.id ? this.id : 'unset') + '이다';

});

  • $('input').attr(

{ value: '', title: '값을 입력하세요.' }

); - value title등 설정

3.1.4 어트리뷰트 제거하기

  • removeAttr(name) - 자바스크립트 DOM 엘리먼트에서 대응하는 프로퍼티가 제거되는 것이 아니 값이 변경될 뿐이다.

3.1.5 어트리뷰트 가지고 놀기

  • $("form").submit(function() {

$(":submit", this).attr("disabled", "disabled");

}); - form의 submit 버튼을 비 활성화

 

3.2 엘리먼트 스타일 변경하기

3.2.1 클래스 추가하고 제거하기

  • addClass
  • removeClass
  • toggleClass
  • $('tr').toggleClass('striped'); - 번갈아 가며 클래스를 적용

3.2.2 스타일 얻고 설정하기

  • $("div.expandable").css("width", function() {

return $(this).width() + 20 + "px";

});

  • $("div.myElements").width(500); - $("div.myElements").css("width", "500px")와 같은 코드
  • $("div.myElements").height(500);
  • var val = $("div.myElements").width(); - 가져오기

3.2.3 스타일과 과련된 유용한 커맨드

  • $("p:first").hasClass("surpriseMe") - 클래스를 갖는지 true false 반환
  • $("p:first").is(".surpriseMe") - 위와 같은 코드
  • $("p:first").attr("class").split(" "); - 앨리먼트에 정의된 클래스 목록을 공백으로 구분된 문자열대신 배열로 얻음(undefined 발생 할 수 있다. 아래로 해결 )
  • $.fn.getClassNames = function() {

if(name == this.attr("className")) {

return name.split(" ");

}

else {

return [];

}

};

3.3 엘리먼트 콘텐츠 설정하기

3.3.1 HTML과 텍스트 콘텐츠 대체하기

  • html(text)
  • var text = $('#theList').text();

3.3.2 엘리먼트 복사하기와 이동하기

  • $('p').append('<b>테스트<b>');
  • $("p.appendToMe").append($("a.appendMe"))
  • $('#flower').appendTo('#targets p:first') - 확장집합의 모든 엘리먼트를 target의 끝으로 이동
  • prepend(), prependTo() - append(), appendTo()와 유사하게 동작하지만 대상 엘리먼트 앞에 삽입
  • before(), insertBefore() - 엘리먼트를 대상의 첫번째 자식으로 삽입하는 대신 대상의 바로앞 형제로 삽입
  • after(), insertAfter() - 엘리먼트를 대상의 마지막 자식으로 삽입하는 대신에 대상의 바로뒤 형제로 삽입

3.3.3 엘리먼트 감싸기

  • $("a.surprise").wrap("<div class='hello'></div>") - surprise 클래스가 있는 링크를 hello클래스를 지닌 div로 감싼다.
  • $("a.surprise").wrap($("div:first")[0]); - 첫번째 <div>엘리먼트를 복사하여 감싼다.
  • .wrapAll() - 일치하는 모든 엘리먼트를 감싼다.
  • .wrapInner() - 일치하는 엘리먼트의 텍스트 노드를 포함한 콘텐츠를 감싼다.

3.3.4 엘리먼트 제거하기

  • $("div.elementToReplace").after("<p>div를 대체한다.</p>").remove(); - 뒤에 추가하고(after 원본 반환) 앞을 제거함 (대체되는 것 같음)
  • $.fn.replaceWith = function(html) {

return this.after(html).remove();

}; - 이렇게 만들어서 확장 사용 가능

  • $("div.elementToReplace").replaceWith("<p> div를 대체한다.</p>"); - 위에서 확장해 사용

3.3.5 엘리먼트 복사하기

  • $('img').clone().appendTo('fieldset.photo'); - 모든 이미지 엘리먼트를 복사해서 photo클래스 fieldset에 붙인다.
  • $('ul').clone().insertBefore('#here').end().hide(); - 복사본 삽입후 원본 감추기

3.4 폼 엘리먼트 값 다루기

  • .val() - 첫번째 엘리먼트의 value 프로퍼티 반환
  • $('[name=radioGroup]:checked]').val(); - 첫 엘리먼트만 처리하므로 체크박스 그룹 사용 어려움. serialize()커맨드나 공식 Form 플러그인을 사용하는 것이 좋다.
  • .val(value) - 값을 설정
  • $('input, select').val(['하나', '둘', '셋']); - input과 select 엘리먼트를 찾아 발견된 체크박스, 라디오버튼, 옵션을 선택 (알아서 선택하니 편리)
     

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

  • jQuery는 우리에게 익숙한 CSS문법을 사용한다.
  • jQuery 정의 메서드 역시 CSS문법을 확장해서 사용한다.

2.1.1 기본 CSS 셀렉터 사용하기

  • a - 모든링크(<a>) 엘리먼트와 일치하는 셀렉터
  • #specialID - specialID를 아이디로 가지는 엘리면트와 일치 셀렉터
  • .specialClass - specialClass를 클래스로 가지는 셀렉터
  • a#specialID.specialClass - 아이디가 specialID이고 specialClass를 클래스로 가지는 링크와 일치하는 셀렉터
  • p a.specialClass - <p> 에리먼트 내에 선언되고 specialClass를 클래스로 가지는 모든링크와 일치하는 셀렉터
  • 몇몇 예외사항을 제외하고 CSS3를 완벽하게 준수한다.

2.1.2 자식셀렉터, 컨테이너 셀렉터, 어트리뷰트 셀렉터

  • p > a - 자식셀렉터
  • a[href^=http://] - 어트리뷰트 셀렉터 (^)는 값의 시작부분이 일치함을 의미함
  • form[method] - 특정 어트리뷰트를 가진 셀렉터 선택
  • input[type=text] - 일치하는 어트리뷰트를 가짐
  • a[href$=.pdf] - 끝값이 일치하는 어트리뷰트 셀렉터
  • a[href*=jquery.com] - 문자열을 포함하는 어트리뷰트 셀렉터
  • li:has(a) - <a>엘리먼트를 포함하는 모든 <li>엘리먼트와 일치한다.

2.1.3 위치로 선택하기

  • :first - 첫번째 일치 엘리먼트
  • :last - 마지막 일치 엘리먼트
  • :first-child - 첫번째 자식 엘리먼트
  • :last-child - 마지막 자식 엘리먼트
  • :only-child - 형제가 없는 엘리먼트
  • :nth-child(n) - n번째 자식 엘리먼트
  • :nth-child(even|odd) - 짝수 또는 홀수 자식 엘리먼트
  • :nth-child(Xn+Y) - 공식에 따른 엘리먼트 ex)li:nth-child(3n)
  • :even / :odd -  짝수 홀수 엘리먼트
  • :eq(n) - n번째 일치 엘리먼트 (인덱스 0부터 시작)
  • :gt(n) - n번째 엘리먼트(포함되지 않음) 이후의 엘리먼트와 일치
  • :lt(n) - n번째 엘리먼트(포함되지 않음) 이전의 엘리먼트와 일치
  • 자식셀렉터는 1부터 시작

2.1.4 jQuery 정의 셀렉터 사용하기

  • :animated - 에니메이션 적용된
  • :button - 모든 버튼
  • :checkbox - 체크박스엘리먼트
  • :checked - 선택된 체크박스
  • :contains(foo) - 문자열 foo를 포함하는 엘리먼트
  • :disabled - 비활성화 상태인 모든 폼엘리먼트
  • :enabled - 활성화 상태인 모든 폼엘리먼트
  • :file - 파일엘리먼트
  • :header - 헤더 엘리먼트
  • :hidden - 감춰진 엘리먼트
  • :image - 폼 이미지 선택
  • :input - 폼 엘리먼트만 선택(input, select, textarea, button)
  • :not(filter) - 필터의 값을 반대로 변경
  • :parent - 빈 엘리먼트 제외 텍스트포함 자식엘리먼트를 가지는 엘리먼트
  • :password - 패스워드 엘리먼트
  • :radio - 라디오 버튼
  • :reset - 리셋 버튼
  • :selected - 선택된 엘리먼트
  • :submit - 전송 버튼
  • :text - 텍스트 엘리먼트
  • :visible - 보이는 엘리먼트

2.2 새로운 HTML 생성하기

  • $("<div>안녕</div>")
  • $("<div>") 는 $("<div></div>")와 같다
  • .appendTo() 메서드도 있다.

2.3 확장된 엘리먼트 집합 관리하기

2.3.1 확장된 집합의 크기 결정하기

  • $('#someDiv').html('페이지에는 총 '+$('a').size() + '개의 링크가 있다');
  • 확장집합의 엘리먼트 개수

2.3.2 확장 집합에서 엘리먼트 획득하기

  • $('img[alt]')[0] - 배열을 이용
  • $('img[alt]').get(0) - 위와 동일. 0 생략시 배열 반환
  • $('img').index($('img#findMe')[0]) - 이미지들중 id가 findMe인 이미지가 몇번째인지 인덱스를 반환

2.3.3 확장 엘리먼트 집합 재편성하기

  • $('img[alt]').add('img[title]') - 엘리먼트를 확장집합에 추가한다.
  • $('p').add('<div>안녕!</div>') - 새 html 생성해서 추가
  • $('img'[title]').not('[title*=puppy]') - title 어트리뷰트를 지닌 모든 img엘리먼트 선택할때 puppy를 포함은 제외(true를 제외)
  • $('img').addClass('seeThrough').filter('[title*=dog]') - not 메서드와는 반대의 결과 (부합하지 않는 false를 제외)
  • $('*').slice(0,4); - 전체 엘리먼트에서 처음부터 4개의 엘리먼트를 포함한 집합생성
  • $('*').slice(4); - 4개 이후(5번째 부터)에서 끝까지의 확장 집합생성

2.3.4 관계를 이용해 확장집합 얻기

  • children() - 고유한 자식으로 구성된 확장집합 반환
  • contents() - 엘리먼트 콘텐츠로 구성된 확장집합 반환. 주로 iframe 엘리먼트 콘텐츠를 얻고자 함(텍스트 노드포함)
  • next() - 확장집합내의 각 확장 엘리먼트 바로 다음에 나오는 형제
  • nextAll() - 확장집합내의 각 확장 엘리먼트 다음에 나오는 모든 형제
  • parent() - 모든 확장 엘리먼트의 바로 위 부모로 구성된 엘리먼트
  • parents() - 모든 확장 엘리먼트의 조상으로 구성된 확장집합 반환(root 미포함)
  • prev() - 각 확장 엘리먼트 바로 이전 형제로 구성된 확장집합
  • prevAll() - 각 확장엘리먼트 이전에 나오는 모든 형제로 구성된 확장집합
  • sibilings() - 확장 엘리먼트의 모든 형제를 포함하는 확장집합을 반환

2.3.5 확장집합을 이용하는 기타 방법들

  • wrappedSet.find('p cite') - wrappedSet 집합에서 <p>에 포함된 <cite>엘리먼트 구성 확장집합
  • var hasImage=$('*').is('img'); - img 엘리먼트가 있는지 true false 반환

2.3.6 jQuery 체인 관리하기

  • $('img').clone().appendTo('#somewhere').end() - appendTo() 이전 확장 집합으로 돌아간다.
  • andSelf() - 커멘드체인에서 이전 확장집합 두개를 하나로 합친다.

 


1.1 jQuery인가?

1.2 튀지 않는 자바스크립트

  •  쉽게 동작을 분리해 낼 수 있도록 라이브러리를 설계 
  • 튀지 않는(unobstrusive) 자바스크립트는 HTML 페이지의 <body>테그에 포함된 자바스크립트 표현식이나 구문을 잘못된 것으로 본다. 
  • 이는 명확하게 책임을 분리해주지만 많은 코드를 짜야하는 비용이 따른다. 
  • jQuery를 이용하면 튀지 않는 자바스크립트 적용한 페이지를 작성하는 일이 한층 쉽고 즐거운 작업이 될 수 있다. 
  •  적은 코드로 코딩이 가능하다.

1.3 jQuery 기초

1.3.1 jQuery() 함수

  • p a  -  <p> 엘리먼트에 포함된 모든링크(<a> 엘리면트)의 그룹을 참조한다.
  • CSS에서 사용되는 일반적인 셀렉터 이외에도 대부분의 브라우저에서 아직 완벽히 구현하지 못한 강력한 셀렉터도 지원한다. CSS3도 지원
  • $()는 jQuery() 함수의 별칭
  • $("div.notLongForThisWorld").fadeOut() -> 사라지게 한후 동일한 엘리먼트 그룹 반환
  • $("div.notLongForThisWorld").fadeOut().addClass("removed"); -> 무한대로 연결가능
  • $("#someElement").html("엘리먼트에 텍스트를 추가한다."); -> 작업이 복잡할 수록 jQuery체인을 사용하면 우리가 원하는 결과를 얻는데 필요한 코드의 양이 확연히 준다.
  • $("#someElement")[0].innerHTML = "엘리먼트에 텍스트를 추가한다."); -> 배열처럼 사용 할 수 있다.

1.3.2 유틸리티 함수

1.3.3 문서 준비 핸들러

  • window.onload는 DOM트리 생성 후 모든 이미지와 다른 외부리소스까지 로드 후에야 실행되므로 이미지나 다른 리소스를 로드하는데 시간이 오래걸리게되면 방문자가 그만큼 기다려야 하므로 전체 페이지에 사용 하기는 어렵다.
  • jQuery는 크로스 브라우져 환경으로 이를 지원
  • $(document).ready(function){     }); - ready()메서드를 통해 ready상태가 되었을때 호출
  • $(function({       }); - DOM이모두 로드될 때까지 코드실행을 기다린다. 문서내에 여러번 사용 가능
  • window.onload는 오직 한 함수만 허용한다.

1.3.4 DOM 엘리먼트 생성하기

  • $("<p>안녕!</p>").insertAfter("#followMe");

1.3.5 jQuery 확장하기

  • jQuery 라이브러리에는 필요한 기능만을 포함시켰다.
  • 필요한 기능을 확장해서 사용 가능하다.
  • $("form#myForm input.special").disable();
  • $.fn.disable = function() {                                                             // disable 함수를 추가하겠다.

retun this.each(function() {

    if (typeof this.disabled != "undefined") this.disabled = true; // this는 위와 다른 this

});

}

1.3.6 다른 라이브러리들과 함께 jQuery 사용하기 

 

1. FullCalendar

FullCalendar is a famous jQuery calendar plugin which offers features like drag-and-drop, integration with Google Calendar and able to fetch events through JSON. Designers can easily customize the look and feel of the calendar, while developers can utilize the exposed hooks for user-triggered events.
FullCalendar

2. Astonishing iCal-like Calendar

This is a tutorial which uses both jQuery and CSS to build an iPhone styled calendar application. The author also implement the Coda-like effect for the popup event.
Astonishing iCal-like Calendar

3. jQuery UI Datepicker

The jQuery UI Datepicker is a highly configurable plugin that adds date picker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.
jQuery UI Datepicker

4. jMonthCalendar

jMonthCalendar supports full month calendar and events. The interesting part of this plugin is it allows developers to interact with the calendar.
jMonthCalendar

5. Date Picker

Date Picker is a jQuery calendar plugin released under MIT and GPL licenses. It has a lot of options and features. For example, you can have multiple calendars in the component, mark dates as special days, easy to customize through CSS and allow different selection modes. All these can be easily setup though the configuration options.
Date Picker

6. jQuery Week Calendar

jQuery Week Calendar is a plugin which will include a weekly calendar in the web application. The events can be supplied as an array or JSON, and these events can be easily drag, drop and resize. There are a lot of options and event callbacks which you can refer through the official plugin page.
jQuery Week Calendar

7. Simple jQuery Date-picker Plugin

This is a very simple date picker plugin. However, it provides a lot of useful and necessary features for a date picker. For example, you can easily navigate to the months and years through the drop down selection boxes.
Simple jQuery Date-picker Plugin

8. jQuery Date Picker Plugin

This is an clean, unobtrusive plugin for jQuery which allows you to easily add date picker to your web forms and pages. There are a lot of configurations and options for this simple plugin. You can refer to the plugin page for more examples of how to use this plugin.
jQuery Date Picker Plugin

9. jQuery Interactive Date Range Picker

This powerful date range picker is a modified version of jQuery UI’s Datepicker component. It has a quicker date selection from a list of preset dates/ranges and a smooth transitions. The latest version uses the jQuery UI 1.7 and jQuery UI CSS Framework. With the power of jQuery UI, user can now switch the calendar theme easily.
jQuery Interactive Date Range Picker


//================================================
// 메일 발송전 폼 체크
// 2009-11-06
// kdonghwa
//================================================
function formCheck() {
    if (jQuery('#fromMail').val().length == 0) {
        alert('발송 메일 주소를 적어주세요');
        jQuery('#fromMail').focus();
        return false;
    }
    if (jQuery('#title').val().length == 0) {
        alert('메일 제목을 적어주세요');
        jQuery('#title').focus();
        return false;
    }
    if (jQuery('#content').val().length == 0) {
        alert('메일 내용을 적어주세요');
        jQuery('#content').focus();
        return false;
    }
    return true;
}

//================================================
// 메일 발송Ajax
// 2009-11-06
// kdonghwa
//================================================
function sendMail() {
    var options = {
        beforeSubmit: formCheck,
        success: responseCtl,
        url: "/url.do",
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        type: "post", /* get, post */
        dataType: "html" /* xml, html, script, json */
    };
    jQuery("#fmMailInfo").ajaxSubmit(options);
}

//================================================
// 메일 발송결과 처리
// 2009-11-06
// kdonghwa
//================================================
function responseCtl(html, status) {
    if (status == 'success') {
        alert('메일을 발송하였습니다.');
        self.close();
    }
    else {
        alert('메일 발송에 실패하였습니다!');
    }
}



 jQuery(document).ready(function() {
         //=========================================================
         // 체크 박스 클릭시 전체 선택 or 전체 선택 해제
         //=========================================================
         jQuery("#check_all").click(function() {
                if (jQuery("#check_all:checked").length > 0) {
                     jQuery('input:checkbox[name=userCheck]:not(checked)').attr("checked", "checked");
                } else {
                    jQuery('input:checkbox[name=userCheck]:checked').attr("checked", "");
                }
         });
 });

 

기본적으로는 서버와 클라이언트 코드는 서로를 직접적으로 호출 할 수 없다. 서로 실행되는 시간과 위치가 다르기 때문이다.

서버코드 : Requeset를 받았을때 서버에서 실행

클라이언트코드 : Response를 받은 클라이언트 브라우저에서 실행

 

하지만, 이를 가능하게 하는 몇가지 방법이 있고, 매번 기억하기 어려워서 여기에 정리해본다.

뭐 고급유저라면 관련 Tip을 상당히 여러가지 알고 있겠지만, 그래도 모든걸 항상 기억하긴 여러우니까...

<작성: http://blog.naver.com/myfancy>

 

1. ASP.NET AJAX - Web Service 호출

스크립트에서 Web Service 컨테이너에서 노출하고 있는 함수를 AJAX로 호출하는 방법이다. 포스트백이나 페이지 리프레시가 발생하지 않는다. 하지만, 비교적 많은 이해가 필요하고, .asmx로 웹서비스를 별도로 만들어야만 된다.

참고) Client-Side Web Service Call with AJAX Extentions

         http://msdn.microsoft.com/en-us/magazine/cc163499.aspx

        Calling Web Servivce from Client Script

         http://msdn.microsoft.com/en-us/library/bb398995.aspx

         http://msdn.microsoft.com/ko-kr/library/bb398998.aspx

 

2. ASP.NET Ajax Extentions - PageMethod 호출

PageMethod는 기본적으로 Page의 Behind코드에 public static으로 노출하고, JavaScript에서 호출하는 방식이다. PageMethod는 [WebMethod]라고 함수에 꾸며주기만 하면되고, Response에 Inline JavaScript Proxy 코드가 생성된다.

 

[System.Web.Services.WebMethod]
public static string GetContactName(string custid){}
함수는 반드시 public static이여야 한다.
 

<asp:ScriptManager ... EnablePageMethods=”true”/>

이 기법을 사용하기 위해서는 ScriptManager에 EnablePageMethods속성을 true로 설정하면 된다.

 

function CallGetContactName(custid,cbParam)
{    
 // call server side method
 PageMethods.GetContactName(custid,OnSuccess,OnFailed,cbParam);
}
// set the destination textbox value with the ContactName
function OnSuccess(res, cbParam)
{    
 //결과값 : res, 콜백파라미터:cbParam
}
// alert message on some failure
function OnFailed(res, cbParam)
{
 //결과값 : res, 콜백파라미터:cbParam
 alert(res.get_message());
}
스크립트를 별도의 파일로 추가할 경우 <head/>섹션이 아닌 <body>태그 아래 추가해야 한다.

3. jQuery를 이용한 WebService 호출

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/

 

4. Get, Post를 이용한 방법 (Non Ajax)

ASP.NET의 Page, HttpHandler, HttpModule등을 이용하여 Request를 받아 Response를 주는 인스턴스를 만들어 놓고, 순수 Ajax나, Post등의 기법을 이용하여 처리 할 수 있다.


If you read this blog you probably know that besides the web user interface, SharePoint also exposes some interfaces which you can use from code: the SharePoint object model and the SharePoint web services. The object model of SharePoint can only be used by code/applications that are running on a SharePoint server in your Server Farm, so you can’t use the object model on client machines. The SharePoint web services can be used of course across a network boundary, that’s what they are built for! In this post I’m going to show you how you can access the out-of-the-box SharePoint web services by making use of the jQuery Javascript library. First let’s see what you can do with this technique: download this zip file that contains an ASPX page (a basic Site Page without any code behind), and the jQuery Javascript library (in case you don’t have it already). Upload the two individual files (not the zip file) in the root of a Document Library in any of your SharePoint sites. You can do this by making use of the web user interface; you don’t have to touch anything on the server itself. When done, just click on the link of the uploaded ASPX and you’ll see following page:


 
Probably you’re not really impressed but think about the fact that this page is just an ASPX file you’ve uploaded through the web user interface, there is absolutely no code behind involved (which would have been blocked by SharePoint’s default security settings). The details of the SharePoint lists are loaded by making use of Javascript code that calls the web SharePoint lists.asmx web service.

So how do you call a SharePoint web service in Javascript code; well you can use the XmlHttpRequest object and write lots of boring code, or you can make use of a Javascript library that wraps this XmlHttpRequest object and exposes a nice and easy interface. In this demo I’ll use the jQuery Javascript library, so the first thing that you’ll need to do is to make sure the page is loading that library:

<script type="text/javascript" src="jquery-1.3.2.min.js" mce_src="jquery-1.3.2.min.js"></script>

If you already configured your SharePoint site so the jQuery library is loaded (for example by making use of the SmartTools.jQuery component), you can skip this line of course. 

When the page is loaded, the Lists web service (e.g. http://yoursite/_vti_bin/lists.asmx) of SharePoint needs to be called; this can be accomplished by making use of the jQuery’s ajax method. This method can post the necessary SOAP envelope message to the Lists web service. The XML of the SOAP envelope can easily be copied from the .NET web service test form of the desired web method (e.g. http://yoursite/_vti_bin/lists.asmx?op=GetListCollection). In the code below, a call to the GetListCollection web method is made when the page is loaded. The complete parameter of the ajax method is actually a pointer to another Javascript function (which we’ll implement later on) that will be called asynchronously when the web service call is done.  Don’t forget to update the url parameter with your SharePoint site’s URL!

$(document).ready(function() {
    var soapEnv =
        "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
            <soapenv:Body> \
                <GetListCollection xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                </GetListCollection> \
            </soapenv:Body> \
        </soapenv:Envelope>";

    $.ajax({
        url: "
http://yoursite/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });
});

As I already mentioned, the processResult function is called when the response XML of the web service call is received. In this method a loop is created which will iterate over every List element of the response XML. For every List element a <li></li> element is added to the element with the ID attribute set to data.

function processResult(xData, status) {
    $(xData.responseXML).find("List").each(function() {
        $("#data").append("<li>" + $(this).attr("Title") + "</li>");
    });
}

This data element is the actual <ul></ul> list in HTML:

<ul id="data"></ul>

When you put everything together in a Site Page, this is the result:


 
In the zip file mentioned in the beginning of this post, you can find an extended version of the processResult function which will display some additional metadata for every list (like the ID, ItemCount etc). The entire contents of basic version of the Site Page built in this post goes as follows:

<%@ Page Language="C#" MasterPageFile="~masterurl/default.master" %>

<asp:Content runat="server" ContentPlaceHolderID="PlaceHolderAdditionalPageHead">

    <script type="text/javascript" src="jquery-1.3.2.min.js" mce_src="jquery-1.3.2.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            var soapEnv =
                "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                    <soapenv:Body> \
                        <GetListCollection xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                        </GetListCollection> \
                    </soapenv:Body> \
                </soapenv:Envelope>";

            $.ajax({
                url: "
http://yoursite/_vti_bin/lists.asmx",
                type: "POST",
                dataType: "xml",
                data: soapEnv,
                complete: processResult,
                contentType: "text/xml; charset=\"utf-8\""
            });

        });

        function processResult(xData, status) {
            $(xData.responseXML).find("List").each(function() {
                $("#data").append("<li>" + $(this).attr("Title") + "</li>");
            });
        }
    </script>

</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="PlaceHolderMain">
    <ul id="data"></ul>
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea">
    List Details
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="PlaceHolderPageTitle">
    List Details
</asp:Content>

+ Recent posts