98..Etc/jQuery2015. 1. 13. 19:16
반응형

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">

<script type="text/javascript">

$(function() {

    $('.date-picker').datepicker( {

        changeMonth: true,

        changeYear: true,

        showButtonPanel: true,

        dateFormat: 'MM yy',

        onClose: function(dateText, inst) { 

            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();

            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

            $(this).datepicker('setDate', new Date(year, month, 1));

        }

    });

});

</script>

<style>

.ui-datepicker-calendar {

    display: none;

    }

</style>

</head>

<body>

    <label for="startDate">Date :</label>

    <input name="startDate" id="startDate" class="date-picker" />

</body>

</html>

Posted by 1010
98..Etc/jQuery2015. 1. 13. 18:58
반응형
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>datepicker demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
</head>
<body>
<div id="datepicker"></div>
<script>
$( "#datepicker" ).datepicker();
</script>
</body>
</html>

-----------------------------------------

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<link rel="stylesheet" href="/resources/demos/style.css">

<style type="text/css">

.ui-datepicker-calendar {

    display: none;

}​

</style>

<script>

$(document).ready(function() {

   $('#txtDate').datepicker({

     changeMonth: true,

     changeYear: true,

     dateFormat: 'MM yy',


     onClose: function() {

        var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();

        var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

        $(this).datepicker('setDate', new Date(iYear, iMonth, 1));

     },


     beforeShow: function() {

       if ((selDate = $(this).val()).length > 0) 

       {

          iYear = selDate.substring(selDate.length - 4, selDate.length);

          iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), 

                   $(this).datepicker('option', 'monthNames'));

          $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));

          $(this).datepicker('setDate', new Date(iYear, iMonth, 1));

       }

    }

  });

});

</script>

<input type="text" id="txtDate">


-----------------------------------------------------


jQuery UI Datepicker is a great control. The default behavior of the control shows dates along with Month and Year. But today for my requirement, I need to show only Month and Year as dropdown (with no dates). So when datepicker control is opened there should be only Month and Year dropdown. This was a bit challenging but after sometime I was able to achieve this.


How to do it?


First of all, hide the calendar area with dates. This can be done by setting "display:none" to ".ui-datepicker-calendar" CSS class. This class is responsible for styling the Date part area of the Calendar.

1.ui-datepicker-calendar {
2    display: none;
3}​

Now,

  • Set changeMonth and changeYear to true so that Month and Year appear as Dropdown.
  • Set date format to "MM yy".
  • jQuery DatePicker has "onClose" event, which is called when Datepicker gets closed. So using this event, fetch the selected Month and Year and setDate of Datepicker.
  • jQuery DatePicker also has "beforeShow" event, which is called before the datepicker is displayed. So this event will be used to Show the previously selected Month and Year as selected. If you don't use this event, then datepicker will always show the current month and current year, irrespective of your previous selection.
01$(document).ready(function() {
02   $('#txtDate').datepicker({
03     changeMonth: true,
04     changeYear: true,
05     dateFormat: 'MM yy',
06 
07     onClose: function() {
08        var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
09        var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
10        $(this).datepicker('setDate'new Date(iYear, iMonth, 1));
11     },
12 
13     beforeShow: function() {
14       if ((selDate = $(this).val()).length > 0)
15       {
16          iYear = selDate.substring(selDate.length - 4, selDate.length);
17          iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5),
18                   $(this).datepicker('option''monthNames'));
19          $(this).datepicker('option''defaultDate'new Date(iYear, iMonth, 1));
20          $(this).datepicker('setDate'new Date(iYear, iMonth, 1));
21       }
22    }
23  });
24});​

See result below. 



If you want to show the buttonPanel as well (see below image) then set "showButtonPanel: true" in DatePicker options.


Feel free to contact me for any help related to jQuery, I will gladly help you.

Posted by 1010
98..Etc/jQuery2014. 5. 21. 15:46
반응형

출처 : http://jhoonslife.tistory.com/524


jqGrid postData 처리시 주의 사항 !


jqGrid 에서 postData 처리를 위해서는 javascript 객체 형식을 써야 합니다.


좋은예와 안좋은예를 보여드리겠습니다.


안좋은예


$("#grid").jqGrid({

  url:'url.do'

, datatype: 'json'

  , mtype: 'POST'

  , page : 1

  , rowNum : 10

postData : "param1="+$("#param1").val() + "&param2="+$("#param2").val()

...



좋은예

$("#grid").jqGrid({

  url:'url.do'

, datatype: 'json'

  , mtype: 'POST'

  , page : 1

  , rowNum : 10

        , postData : { 

jobReqId:$("#jobReqId").val(), 

srcWkptId:$("#selSrcWkptId").val() 

}...



두가지의 차이점은 
postData 를 full text 로 입력 했느냐, 자바스크립트 객체로 입력 했느냐 입니다.

어떻게 보면 두가지 모두 비슷한 결과를 나타내는것 같지만
전달되는 요청관계를 자세히 살펴보면 전혀 다른 결과가 나타납니다.

안좋은예의 요청 파라미터
param1=param1&param2=param2

좋은예의 요청 파라미터

param1=param1&param2=param2&_search=false&nd=1353343119211&rows=10&page=1



두가지의 차이를 아시겠나요?
안좋은예는 정말 postData 안에 있는 항목만 파라미터로 담겨서 넘어갑니다. jqGrid 의 다른 속성 컬럼들이 파라미터에 담기질 않습니다.
(이유는 잘 모르겠습니다. 아는사람 설명 좀 부탁해요.)
그래서 당연히 페이징이랑 검색이 자연스럽게 넘어가지 않았던 거죠~!

그렇지만 자바스크립트 객체로 입력해 놓은 좋은예는 postData 뿐만아니라 jqGrid 의 다른 여러가지 프로퍼티들도 함께 넘어갑니다 ( 페이징처리 시에 필요한 rows 와 page 까지 함께..)

그렇기 때문에 첫번째 페이지가 나오는건 같은데 페이징 처리가 먹히지 않는 것은 postData 처리를 잘못 하였기 때문입니다.

postData 는 반드시 full TEXT 가 아닌 자바스크립트 객체 형식으로 넘기셔야 하고, 검색이나 페이징 시에도 마찬가지 입니다.

reload 의 나쁜예

$("#"+gridId).setGridParam({

page : pageNum,

rowNum : rowNum,

postData : "param1="+$("#param1").val()+"&param2="+$("#param2").val()

}).trigger("reloadGrid");



reload 의 좋은예

$("#"+gridId).setGridParam({

page : pageNum,

rowNum : rowNum,

postData : {

param1:$("#param1").val(),

param2:$("#param2").val()

}

}).trigger("reloadGrid");


-끝


Posted by 1010
98..Etc2014. 4. 7. 13:43
반응형

http://update.zeroturnaround.com/update-site-archive/

Posted by 1010
98..Etc2014. 4. 2. 00:35
반응형

http://hanho9.cafe24.com 나오는 2번에 스크립트 경로를 아래에 스크립트에 적용후 


javascript:(function(e){e.setAttribute("src","http://debug-software.intel.com/target/target-script-min.js#anonymous");document.getElementsByTagName("head")[0].appendChild(e);})(document.createElement("script"));void(0);


실제 디버깅할 곳에 삽입

------------------------------------------



http://debug-software.intel.com/

http://debug.phonegap.com/



Tutorial-UsingDebugMobi.pdf




 

 

 

 

 

 

 

 

 

 

 

 

Intel® HTML5 Development Environment 

Tutorial – Using App Debugger 

v1.05 : 03.06.2013 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

Legal Information 

INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, 

EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS 

GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR 

SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR 

IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR 

WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR 

INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. 

A "Mission Critical Application" is any application in which failure of the Intel Product could result, 

directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS 

FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS 

SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES 

OF EACH, HARMLESS AGAINST ALL CLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE 

ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, 

PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, 

WHETHER OR NOT INTEL OR ITS SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR 

WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS. 

Intel may make changes to specifications and product descriptions at any time, without notice. 

Designers must not rely on the absence or characteristics of any features or instructions marked 

"reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility 

whatsoever for conflicts or incompatibilities arising from future changes to them. The information here 

is subject to change without notice. Do not finalize a design with this information. 

The products described in this document may contain design defects or errors known as errata which 

may cause the product to deviate from published specifications. Current characterized errata are 

available on request. Contact your local Intel sales office or your distributor to obtain the latest 

specifications and before placing your product order. Copies of documents which have an order number 

and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-

4725, or go to: http://www.intel.com/design/literature.htm 

Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries. 

*Other names and brands may be claimed as the property of others. 

Microsoft, Windows, and the Windows logo are trademarks, or registered trademarks of Microsoft 

Corporation in the United States and/or other countries. 

Copyright © 2013, Intel Corporation. All rights reserved. Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

1.0 Purpose 

The purpose of this documentation is to demonstrate how to use the App Debugger tool to remotely 

debug HTML5 code over the Internet. The App Debugger tool is based on an open source tool called 

“Web Inspector Remote”* (WEINRE) that provides remote Web debugging for mobile devices. 

However, App Debugger is a configuration-free hosted version of that software that anyone can use for 

free across the Internet. 

2.0 How to Use App Debugger 

To use the App Debugger tool, browse to http://debug-software.intel.com in your Google* Chrome web 

browser. 

 

A unique identifier is generated automatically for you. If you were returning to App Debugger after 

debugging previously, you might instead enter your current unique ID. 

Once you have determined the unique id that will be used for the current debugging session, make sure 

that your HTML5 project has the listed script included in it. It could go anywhere, but for consistency it 

is typically placed just after the closing body tag in your HTML document. 

 

<html><body></body> 

<script src="http://debug.html5m.com/target/target-script-min.js#ac4928aa-418b-d4c8-

5839-1a6b278c0146"></script></html> 

 

 

Next, click the link to start App Debugger on your Chrome* browser. That will bring up a remote page 

that looks something like this: Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

 

There are no targets yet. Once the JavaScript* library is loaded into an HTML5 page, that page will show 

up as one of the available targets in just a few seconds. 

 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

Once the target has fetched the WEINRE JavaScript from the server, executed it, and made a good 

contact back to the App Debugger server, the Target will turn green. 

 

If you have several Targets, select the one you want to view. You should then be able to use Chrome’s 

debugging tools similar to how one would use those tools to debug local JavaScript. Switch to the 

Console view within Chrome to see the console.log messages coming from the remote JavaScript. 

 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

3.0 Finding Bugs 

The App Debugger tool can help you to find bugs in your remote JavaScript/HTML code in several ways. 

3.1 Capture console.log calls 

Any JavaScript messages logged to the console using console.log will make their way to the App 

Debugger console window. That can save you the heartache of having to write messages to the screen 

as a debug log or putting up a load of annoying alert boxes. In the example below, the HTML5 program 

running on the right is transmitting its console.log calls to the App Debugger window on the left. 

 

 

3.2 Adjust CSS on the Fly 

The App Debugger window also gives you the ability to change CSS elements and immediately see the 

results on the client side. In the example below, the CSS for the title page is adjusted and the result 

plays out immediately on the client window to the right. Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

 

3.3 Adjust JavaScript on the fly 

The App Debugger window gives you the ability to write JavaScript and have it executed immediately on 

the client side. In the example below, the canvas tag which includes the kung-fu fighter is set to be 

transparent, making him appear ghostly in the right window. 

 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

3.4 Inspect HTML 

The App Debugger tool allows you to inspect HTML elements. Highlighting the HTML code in the App 

Debugger window will highlight the element on the client side. In the example below, the HTML 

element for the title is selected for inspection which highlights it in the right-hand execution window. 

 

4.0 More Information 

For more information, check out a quick demonstration video here: 

http://youtu.be/k0t2oZKpmA8 

The App Debugger service is also available as a Chrome extension here: 

http://tinyurl.com/debugmobi-chrome 

For a more detailed explanation of how WEINRE works link here: 

http://muellerware.org/papers/weinre/manual.html 

 

 

Posted by 1010
98..Etc2014. 4. 1. 18:20
반응형

Weinre(와이너 or 와이너리)란?

  server는 java기반의 http서버 (jetty)

  client는  webkit계열의 브라우저 (일반적으로 서버와 같은 pc에서 실행)

  target은 webkit계열의 브라우저 (일반적으로 태블릿, 폰의 브라우저)

  위와같이 구성된 디버깅 라이브러리이고 태블릿과같이 javascript디버깅을 할수없는 기기에서 

  target(태블릿) => server(pc)로 http통신을 하여 client(pc의 브라우저)로 원격 디버깅을 할 수 있습니다.

  참고로 2.0버전부터는 Weinre의 서버가 node.js로 변경 되었습니다만

  여기에서는 java기반 서버의 마지막 버전인 1.6.1로 설명 하겠습니다.


라이센스 : apache license 2.0


사이트

  공식 : http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

  1.6.1다운로드 : http://people.apache.org/~pmuellr/weinre/builds/1.x/1.6.1/weinre-jar-1.6.1.zip


1. weinre.jar파일 실행해서 서버시작 하기

01./* 옵션 */
02.-help (or -? or -h) => 도움말
03.-httpPort [포트번호] => 포트번호 (default 8080)
04.-boundHost [hostname | ip address | -all-] => 서버 ip주소 또는 호스트이름
05.-verbose [true false] => 자세한 내용 출력 (default false)
06.-readTimeout [seconds] => weinre서버가 log내용을 읽어들이는 시간 (default 5초)
07. 
08./* 실행 */
09.java -jar weinre.jar --httpPort 포트번호 --boundHost IP주소 --verbose true



2. weinre client 띄우기

http://weinre서버주소:포트번호/client


3. 개발한 html페이지에 weinre script 삽입후 리로드

1.<script type="text/javascript" src="http://서버주소:포트번호/target/target-script-min.js"></script>


4. weinre client에서 target이 접속되었는지 확인



5. 위와같이 접속이 확인되었으면 디버깅이 가능한 상태입니다.

4번 그림에서의 화면은 webkit의 디버깅창이 아닌 webkit의 디버깅창을 

따라서 비슷하게 만든 weinre의 화면입니다.


출처 : http://kdarkdev.tistory.com/248

Posted by 1010
98..Etc/jQuery2014. 4. 1. 16:47
반응형

출처 : http://findfun.tistory.com/m/post/382


jQuery.ajax()

원문 링크  http://api.jquery.com/jQuery.ajax/

권고사항 : 아래 글을 보시기 전에 권고드립니다. 아래는 발번역과 오역 그리고 미처 다 한글화가 되어있지 않습니다. 의미도 모른채 번역된 부분이 많기 때문에 다 건너띠고 아래쪽 예제만 보시길 강력히 권고 드립니다. 나빠진 정신건강에 대해 책임(?)지지 않습니다. ^^;;;;

jQuery.ajax( url [, settings] )Returns : jqXHR

개요 : 비동기 HTTP (Ajax) 요청을 수행합니다.

  • jQuery.ajax( url [, settings] )
  • url 요청을 보낼 URL 문자열
  • settings key/value 쌍으로 구성된 Ajax 요청 설정값. 모든 값들은 생략이 가능한 옵션값 임. 기본적인 설정값을 $.ajaxSetup() 에 정의할 수 있음. 모든 세팅에 대한 내용이 궁금하시면 jQuery.ajax( settings ) 을 참고하세요.
  • jQuery.ajax( settings )
  • settings key/value 쌍으로 구성된 Ajax 요청 설정값. 모든 값들은 생략이 가능한 옵션값 임. 기본적인 설정값을 $.ajaxSetup() 에 정의할 수 있음.
  • acceptsMap
    Default: 데이터 타입에 의존적 depends on DataType

    content 타입을 헤더에 포함하여 서버에 보내면 응답 시 같은 타입으로 리턴이 됩니다. 만약 accepts 세팅값을 수정하려 한다면 $.ajaxSetup() 함수에서 해야 합니다.

    asyncBoolean
    Default: true

    기본으로 사용하면, 모든 요청은 비동기방식으로 동작합니다. 만일 동기방식으로 사용하려면 이 값을 false로 세팅하세요. 크로스도메인(2개의 도메인 사이의 정보교환)과 dataType: "jsonp" 인 경우는 동기방식이 지원되지 않습니다. 동기방식은 요청이 처리될 때까지 브라우져가 일시적인 잠금상태가 됩니다.

    beforeSend(jqXHR, settings)Function

    요청 전 콜백함수이며, 이 함수에서 요청을 보내기 전 jqXHR 객체를 수정할 수 있습니다. 이 함수에서 false를 반환하면 Ajax 요청이 취소됩니다.jQuery 1.5부터 beforeSend 옵션은 요청의 type에 상관없이 호출할 수 있습니다.

    cacheBoolean
    Default: true, dataType 이 'script' 와 'jsonp' 일때는 false로 세팅

    만일 이 값을 false로 하면, 브라우저의 캐쉬사용을 강제적으로 막습니다. 또한 false 세팅하면 URL 쿼리 스트링에 "_=[TIMESTAMP]" 값이 추가됩니다.

    complete(jqXHR, textStatus)Function, Array

    요청이 완료되었을 때 호출되는 함수입니다. 요청에 대한 응답이 success 나 error 가 반환된 후 실행됩니다. 이 함수는 2개의 인자를 갖습니다. jqXHR 객체와 요청에 대한 상태값("success""notmodified""error""timeout""abort""parsererror")으로 구성되어 있습니다. 더 자세한 내용은Ajax Event를 참고하십시오.

    contents(added 1.5)Map

    문자열과 정규표현식이 쌍으로 이루어진 맵 데이터 입니다. jQuery는 응답 데이터를 이 맵 데이터를 기준으로 파싱합니다.

    contentTypeString
    Default: 'application/x-www-form-urlencoded'

    서버에 데이터를 보낼 때 사용되는 content-type 입니다. 기본값은 "application/x-www-form-urlencoded" 입니다. 명시적으로 바꾸려면 $.ajax() 함수안에서 content-type을 세팅해 줘야 합니다. 서버로 데이터를 보낼 때는 언제나 UTF-8 charset를 사용합니다. 따라서 서버 사이드 프로그램 시 그에 맞게 디코딩을 하여 사용해야 합니다.

    contextObject

    This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

    $.ajax({
    	  url: "test.html",
    	  context: document.body
    	}).done(function() { 
    	  $(this).addClass("done");
    	});

    converters(added 1.5)Map
    Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}

    데이터 타입을 변환합니다.

    crossDomain(added 1.5)Boolean
    Default: false : 같은 도메인 내의 요청일 경우, true : 크로스 도메인 간의 요청일 경우

    만일 2개의 다른 도메인(CrossDomain)간의 데이터 교환이라면(JSONP와 같은), 이 세팅값을 true로 해야 합니다.

    dataObject, String

    서버로 보낼 데이터입니다. GET 요청 형태의 query 스트링으로 변환되어 보내집니다. GET 요청 파라미터에 자동으로 추가됩니다. 이런 자동 추가를 방지하기 원하면 processData 옵션을 보시기 바랍니다. 이 객체는 key/value의 쌍으로 이루어져 있습니다. 만일 value가 배열이라면, jQuery는 같은 key로 여러 value를 직렬화 구성을 하게 됩니다. 아래쪽에 추가적인 설명이 있습니다.

    dataFilter(data, type)Function

    이 함수는 응답 원시 데이터를 핸들링 할 수 있습니다. 정제된 데이터를 반활해야 할 필요가 있을 때 사용합니다. 두개의 인자가 있는데 data 와 그 데이터의 type입니다.

    dataTypeString
    Default: Intelligent Guess (xml, json, script, or html)

    서버에서 응답 받을 때는 데이터의 타입을 jQuery가 추정하여 처리합니다. 만일 인자를 아무것도 적지 않으면 응답 메시지의 MIME type을 기초로하여 처리하게 되는 것입니다. MIME type이 XML 이며 yield XML을 생성하고, 1.4 JSON은 JavaScript 객체를 생성, 1.4 script라면 script를 실행하고, 그 외 다른 것들은 문자열을 리턴합니다.

    • "xml": jQuery가 XML 문서를 반환합니다.
    • "html": 평문 HTML 을 반환합니다.
    • "script": JavaScript를 실행하고 평문 텍스트를 리턴합니다. 쿼리 스트링에 "_=[TIMESTAMP]" 를 추가하면 캐싱을 방지할 수 있습니다. 이런 방식은cache 옵션을 true로 바꾸는 역할을 합니다.
    • "json": JSON을 JavaScript 객체형태로 반환합니다. jQuery 1.4에서 JSON 데이터는 엄격한 방식으로 파싱되었습니다. 형식에 맞지않는 JSON 데이터는 요청이 거부되고 error을 발생시켰습니다. JSON 포맷에 대해 궁금하시면 json.org 을 방문해 보세요.
    • "jsonp": JSONP 를 사용하여 JSON 블럭을 로드합니다. 쿼리 스트링에 "_=[TIMESTAMP]" 를 추가하면 캐싱을 방지할 수 있습니다. 이런 방식은 cache옵션을 true로 바꾸는 역할을 합니다.
    • "text": 평문 텍스트 문자열을 반환합니다.
    • multiple, 공백 구분 값(space-separated values): jQuery 1.5에서, dataType을 변환할 수 있게 되었습니다. 예를들어 응답받은 text 를 XML 로 변화하고 싶으면, "text xml"이라고 사용하면 됩니다.

    error(jqXHR, textStatus, errorThrown)Function

    요청(request)이 실패하면 호출됩니다. 이 함수는 3개의 인자를 통해 데이터를 받을 수 있습니다. jqXHR 객체는 발생한 에러 타입과 추가적인 예외 사항을 담고 있습니다. 두번째 인자에는 "timeout""error""abort""parsererror" 와 같은 상황을 담고 있습니다. 세번째 인자에는 HTTP 에러가 담겨 있는데, "Not Found" 나 "Internal Server Error." 같은 것 들입니다. Note: cross-domain 스크립트나 JSONP 요청에 대해서는 이 함수를 사용할 수 없습니다.

    globalBoolean
    Default: true

    전역 Ajax 이벤트 핸들러를 제어합니다. 기본값은 true 입니다. 이 값을 false로 하면 ajaxStart 나 ajaxStop 같은 전역 핸들러의 실행을 막을 수 있습니다.

    headers(added 1.5)Map
    Default: {}

    요청 시 추가로 보낼 헤더 정보입니다. key/value 쌍으로 구성됩니다. 이 세팅값은 beforeSend 함수가 호출되기 전에 처리되야 합니다. beforeSend 함수 내에서 value 값을 재조정 할 수 있습니다.

    ifModifiedBoolean
    Default: false

    마지막 request 이후 response가 변경되었을 경우에만 request가 성공하도록 허용하는 값입니다. 이것은 마지막 수정 정보를 헤더에서 체크하는 것입니다. 기본값은 false 이며 이 옵션이 무시됩니다. 즉, 언제나 request에 대한 응답을 체크하는 것입니다. jQuery 1.4 부터는 수정되지 않은 데이터를 알아내기 위한 'etag' 를 체크할 수 있습니다.

    isLocal(added 1.5.1)Boolean
    Default: 현재 프로토콜을 유지 depends on current location protocol

    jQuery에서 인식하지 못하더라도 현재 환경이 "local(예, filesystem)" 로 인식할 수 있도록 허용합니다.(이건 무슨 의미인지 모르겠네요.) 다음 file*-extensionwidget 프로토콜 들은 현재 local로 인식합니다. 만일 isLocal 세팅을 변경을 원하시면 $.ajaxSetup() 함수에서 하실 것을 권장드립니다.

    jsonpString

    jsonp 요청에 사용한 콜백 함수명을 오버라이드 합니다. 이 값은 url에 포함된 쿼리 스트링의 부분인 'callback=?' 문자열 중 'callback' 을 대신하여 사용됩니다. 예를 들면 {jsonp:'onJSONPLoad'} 라고 세팅하면 서버에 'onJSONPLoad=?' 처럼 전달되게 되는 것입니다. jQuery 1.5 부터는 jsonp 옵션을false 로 세팅하여 URL에 "?callback" 이 추가되는 것을 방지하거나 "=?" 을 변조되는 시도를 방지할 수 있습니다. 이러한 경우 명시적으로jsonpCallback 세팅값을 이용하여야 합니다. 예를 들어, { jsonp: false, jsonpCallback: "callbackName" } 와 같이 사용합니다.

    jsonpCallbackString, Function

    JSONP 요청 시 콜백 함수명을 지정합니다. 지정하지 않으면 jQuery에서 임의적으로 부여하게 됩니다. 요청(request)에 대해 쉽게 핸들링 할 수 있도록 유니크한 이름이 부여됩니다. 콜백 이름을 당신이 지정할 수도 있습니다. jQuery 1.5부터 함수명을 세팅할 수 있게 되어습니다.

    mimeType(added 1.5.1)String

    XHR의 마임 타입을 설정합니다.

    passwordString

    HTTP 엑세스 시 패스워드를 설정합니다.

    processDataBoolean
    Default: true

    By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

    scriptCharsetString

    Only for requests with "jsonp" or "script" dataType and "GET" type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

    statusCode(added 1.5)Map
    Default: {}

    요청에 대한 응답 시 전달된 HTTP 상태 코드와 실행될 함수로 이루어진 집합입니다. 예를 들어, 404 상태에 대해 알림창을 보여주는 경우는 아래 예와 같습니다.

    $.ajax({
    	  statusCode: {
    		404: function() {
    		  alert("page not found");
    		}
    	  }
    	});

    만일 요청이 성공했다면, 상태코드는 성공 콜백함수로 같은 파라미터를 전달합니다. 반대로 error 가 발생해도 같은 파라미터를 error 콜백 함수로 전달하게 됩니다.

    success(data, textStatus, jqXHR)Function, Array

    요청이 성공했을 때 호출됩니다. 이 함수는 3개의 인자를 전달합니다. data 인자는 서버에서 전달된 데이터를, 두번째는 데이터의 타입을, 마지막으로 jqXHR(jquery 가 변형한 XMLHttpRequest 객체)를 전달하게 됩니다. jQuery 1.5 부터, success 시 함수 배열을 전달 받을 수 있습니다.

    timeoutNumber

    요청 대기 시간을 세팅합니다.

    traditionalBoolean

    이 세팅값을 true로 하면 전통적인 스타일의 파라미터 직렬화를 사용할 수 있습니다.(이건 뭔가요 ㅡㅡ;;)

    typeString
    Default: 'GET'

    요청 시 POST 와 GET 방식을 결정합니다. 기본값은 GET 방식입니다.

    urlString
    Default: 현재 페이지 The current page

    요청을 보낼 URL 주소입니다.

    usernameString

    HTTP 요청 시 필요한 username 값 입니다.

    xhrFunction
    Default: IE 에서는 ActiveXObject 이고 다른 브라우저는 XMLHttpRequest

    XMLHttpRequest 객체입니다.

    xhrFields(added 1.5.1)Map

    기본 XHR 객체의 키-값의 맵 데이터 입니다. 예를 들어, 크로스 도메인에서 withCredentials 값을 true로 하고 싶다면 아래와 같이 세팅합니다.

    $.ajax({
    	   url: a_cross_domain_url,
    	   xhrFields: {
    		  withCredentials: true
    	   }
    	});

    jQuery 1.5 부터 withCredentials 속성은 네이티브 XHR 에서 전달하지 못합니다.

$.ajax() 함수는 jQuery에서 사용되는 모든 Ajax 의 근간입니다. 종종 이 함수를 직접 호출하지 않아도 쉽게 사용할 수 있는 함수들이 있습니다.$.get() 이나 .load() 같은 함수들이 그것들입니다. 만일 세팅값을 변경할 필요가 있을 경우에도 $.ajax() 함수에서 유연하게 변경할 수 있습니다.

$.ajax();

Note: 기본 세팅값을 전역적으로 관리하려면 $.ajaxSetup() 함수를 이용해야 합니다.

위의 옵션값을 아무것도 없이 사용하면 현재 페이지에서 응답 결과를 제어하지 못합니다. 이게 가능하려면 콜백 함수를 지정해야 합니다.

The jqXHR Object

jQuery XMLHttpRequest (jqXHR) 객체는 $.ajax() 함수에서 반환됩니다. jQuery 1.5 부터 브라우저의 네이티브 XMLHttpRequest 객체의 상위집합 입니다. 예를 들어, 이 객체는 responseText 과 responseXML 속성을 포함하고 있을 뿐만 아니라 getResponseHeader() 함수도 포함하고 있습니다. 전송 메카니즘이 XMLHttpRequest 가 아닌 다른 것일 경우( JSONP 요청에 대한 script 태그 같은) jqXHR 객체는 네이티브 XHR 기능을 이용하게 됩니다.

jQuery 1.5.1부터, jqXHR 객체는 overrideMimeType() 함수를 사용하게 됩니다. (이것은 jQuery 1.4.x 에서는 사용되었지만, jQuery 1.5 에서 일시적으로 삭제되었음). .overrideMimeType() 함수는 method may be used in the beforeSend() 콜백 함수에서 사용될 수 있습니다. 예를 들어, 응답의 content-type header 를 수정하기 위해서 아래와 같이 사용할 수 있습니다.:

$.ajax({
  url: "http://fiddle.jshell.net/favicon.png",
  beforeSend: function ( xhr ) {
    xhr.overrideMimeType("text/plain; charset=x-user-defined");
  }
}).done(function ( data ) {
  if( console && console.log ) {
    console.log("Sample of data:", data.slice(0, 100));
  }
});

$.ajax() 에서 반환된 jqXHR 객체는 jQuery 1.5 의 약속된 인터페이스를 구현하여 모든 속성, 메소드, 동작들을 제공하고 있습니다.(더 많은 정보를 원하시면 Deferred object 를 참고). 편의성과 일관성을 위해 $.ajax() 함수에서 사용될 콜백 함수들로 jqXHR 객체는 .error().success().complete()와 같은 함수들을 사용할 수 있습니다. 이들 함수들은 $.ajax() 요청이 종료되었을 때 호출되고 모두 같은 인자를 전달받게 됩니다. 이것은 단일 요청에서 여러 콜백 함수를 지정할 수도 있고 요청이 완료된 후에도 콜백 함수를 지정할 수 있습니다.

Notice: jqXHR.success()jqXHR.error()jqXHR.complete() 콜백 사용은 1.8 버전부터 사용이 중지됩니다. 이런 사용을 제거하거나 jqXHR.done(),jqXHR.fail()jqXHR.always() 함수들로 대체하십시오.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "example.php" )
    .done(function() { alert("success"); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() { alert("second complete"); });

For backward compatibility with XMLHttpRequest 이전 버젼과의 호환성을 위해, jqXHR 객체는 아래와 같은 속성과 메소드들을 제공합니다.

  • readyState
  • status
  • statusText
  • responseXML or responseText
  • setRequestHeader(name, value)
  • getAllResponseHeaders()
  • getResponseHeader()
  • abort()

하지만 onreadystatechange 매커니즘은 제공되지 않기 때문에 successerrorcompletestatusCode 이 상황들을 모두 커버 해야할 필요성이 있습니다.

Callback Function Queues

beforeSenderrordataFiltersuccesscomplete 옵션들 모두는 적절한 시간에 호출할 수 있는 콜백 함수를 가질 수 있습니다.

jQuery 1.5부터, error (fail), success (done), complete (always) 콜백 함수들은 큐에서 선입선출(first-in, first-out) 방식으로 제어할 수 있습니다. 이 의미는 콜백 함수마다 처리 로직을 수행할 수 있다는 뜻입니다. Deferred object methods 를 참고하여 $.ajax() 함수에서 콜백 시의 내부처리에 대해 알아볼 수 있습니다.

모든 콜백 함수의 this 키워드는 $.ajax 에서 전달된 context 의 객체들을 가르킵니다. 만일 context 가 지정되지 않았다면 this는 Ajax 세팅 자체를 지칭하게 됩니다.

JSONP 나 cross-domain 의 GET 요청 같은 XHR을 사용하지 않는 Ajax 방식을 사용할 경우에 XMLHttpRequest 나 textStatus 파리미터들은 undefined값을 가지게 됩니다.

아래는 $.ajax()에서 콜백 시 발생하는 훅(hook - I/O 시 정의된 상수값들 정도로 생각하면 됨) 값들 입니다.

  1. beforeSend jqXHR 객체와 파라미터 settings 맵을 받습니다.
  2. error 요청이 실패했을 경우 순서대로 등록됩니다. error 타입 문자열과 exception 객체로 구성된 jqXHR 들을 받습니다. 몇몇 Some 내장 error들은 exception 객체에 "abort", "timeout", "No Transport"와 같은 문자열이 넘어옵니다.
  3. dataFilter 성공적으로 응답이 되었을 경우 즉시 호출됩니다. 반환된 데이터와 dataType 을 받을 수 있고 success 쪽으로 변경된 데이터를 전달해야 합니다.
  4. success 요청이 성공하면 요청된 순서에 따라 호출됩니다. 반환된 데이터와 성공 코드를 포함한 문자열 그리고 jqXHR 객체를 받을 수 있습니다.
  5. complete 요청이 실패하거나 성공에 관계없이 요청이 종료되면 순서에 따라 발생합니다. 성공 또는 실패에 대한 코드를 담은 jqXHR 객체를 받습니다.

예를 들어, HTML 이 반환되고 이것을 사용하고 싶다면 success 핸들러를 사용해야 합니다.

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

Data Types

$.ajax() 함수는 검색한 데이터에 대한 정보를 제공하는 서버에 의존합니다. 만일 서버에서 XML 데이터가 제공되었다면, 일반적인 XML 메소드나 jQuery의ㅣ 선택자(selector)들을 사용하여 제어할 수 있습니다. 만일 위의 예제와 같이 HTML 같은 것이라면 데이터를 text 처럼 취급할 수도 있습니다.

별개의 다른 데이터를 dataType 옵션을 이용하여 다룰 수 있습니다. dataType 으로는 xml htmljsonjsonpscripttext.

text 나 xml 타입은 jqXHR 객체의 속성인 responseText 나 responseXML 을 통해 success 핸들러에서 간단하게 받을 수 있습니다.

Note: 웹 서버에서 사용한 MIME 타입과 데이터 요청 시의 dataType 값이 같은지 확인해야 합니다. 특히 XML 은 서버에서 text/xml 또는application/xml 로 반환했는지 확인하고 그에 맞춰 사용해야 합니다.

만일 html 을 지정하는 경우, HTML 이 반환 되기 전에 내부의 JavaScript 는 실행이 된 후 반환이 됩니다. 비슷하게 script 를 정의했다면, 서버에서 반환될 때 인라인 JavaScript 는 실행이 되고 반환되게 됩니다.

json 타입은 The json JavaScript 객체로 가져온 데이터 파일을 분석하고 결과 데이터로 만들어진 객체를 반환합니다. 이렇게 하기 위해서는, 브라우저가 지원한다면 jQuery.parseJSON() 을 사용하거나, 지원하지 않는다면 Function constructor 을 사용해야 합니다. 형식에 맞지 않는(Malformed) JSON 데이터는 에러가 발생하게 되는데 더 많은 정보는 json.org에서 보실 수 있습니다. JSON 데이터는 구조화된 데이터의 이동에 편리합니다. JavaScript 로 처리하기에 간결하고 쉽습니다. 만일 외부 서버에서 가져와야 하는 데이터라면, jsonp 타입을 대신 사용할 수 있습니다.

이 jsonp 타입은 URL 쿼리스트링에 callback=? 이라는 문자열이 추가됩니다. 서버는 유효한 형태의 JSONP 반환 데이터를 콜백(callback) 이름을 사용하여 반환하게 됩니다. $.ajax() 의 옵션인 callback 이외에 다른 파라미터를 지정하여 사용할 수 있습니다.

Note: JSONP 는 확장된 JSON 포맷입니다.

script 나 jsonp 데이터 타입이 사용 가능한 원격 서버에서 데이터를 가져왔을 때, error 콜백과 글로벌 이벤트는 발생하지 않습니다.

Sending Data to the Server

기본적으로, Ajax는 GET HTTP 방식입니다. POST 방식이 필요할 경우, type 옵션값을 이용하면 됩니다. POST 데이터가 서버로 전송될 경우 W3C XMLHTTPRequest 표준인 UTF-8 캐릭터셋을 이용하게 됩니다.

data 옵션값은 key1=value1&key2=value2 형태의 쿼리 스트링을 사용할 수 있습니다. 또한 {key1: 'value1', key2: 'value2'} 형태도 사용이 가능합니다. 만일 후자의 형태를 사용할 경우, 데이터를 보내기 전에 jQuery.param()을 사용하여 데이터를 가공해야 합니다. 이 과정은 processData 을 false로 세팅하면 해결할 수 있습니다. 이 과정을 수행하면 서버로 XML 데이터를 보낼 때 contentType 타입이 application/x-www-form-urlencoded 로 변경되는 것을 방지할 수 있습니다. (음, 이 부부은 사실 명확치 않네요. 좀더 공부가 필요합니다. ㅜㅜ)

Advanced Options

global 옵션으로 .ajaxSend().ajaxError() 그리고 이 함수로 인해 호출되는 함수들의 실행을 제어할 수 있습니다. cross-domain 스크립트와 JSONP 가 사용될 경우에는 자동으로 false 로 세팅됩니다. 더 자세한 내용은 함수들의 사용법을 살펴 보십시오.

만일 서버가 HTTP 인증을 요구한다면 username 과 password 옵션을 사용할 수 있습니다.

Ajax 사용 시 시간제한을 두어 사용자에게 그 내용을 제공하는 것이 좋습니다. 요청시간은 $.ajaxSetup() 에서 timeout 옵션값을 조절하는 것이 좋습니다.

기본적으로 지속적인 요청에 대해 브라우저는 캐시에 있는 결과를 사용하려 합니다. 이런 부분을 해결하기 위해 cache 옵션을 false로 세팅하시기 바랍니다. 또한 결과가 마지막 요청 후에 변경되지 않았다면 ifModified을 true로 세팅하면 false를 반환받을 수 있습니다.

scriptCharset 옵션은 <script> 태그의 캐릭터셋을 명시적으로 설정할 수 있습니다. 만약 서버와 스크립트의 캐릭터 셋이 다를 경우 아주 유용한 옵션입니다.

Ajax 의 기본은 "비동기(asynchronous)" 입니다. async 옵션은 기본적으로 $.ajax() 에서 true 로 세팅되어 있습니다. 이 옵션을 false 로 바꾸면 동기식으로 전환됩니다.

$.ajax() 함수는 XMLHttpRequest 객체를 반환합니다. 일반적으로 jQuery는 내부적으로 이 객체를 처리합니다. 사용자 정의 함수에서는 xhr 의 옵션을 이용해서 가공을 할 수 있습니다. 반환된 객체는 대체로 삭제되지만 저수준 인터페이스에서는 요청에 대한 조작을 위해 사용할 수도 있습니다. 특히,.abort() 를 호출하면 객체가 완성되기 전에 요청을 중단할 수 있습니다.

jQuery.ajaxSettings.xhr 를 오버라이드해서 사용하는 예제입니다.

var _super = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
    var xhr = _super(),
        getAllResponseHeaders = xhr.getAllResponseHeaders;

    xhr.getAllResponseHeaders = function () {
        if ( getAllResponseHeaders() ) {
            return getAllResponseHeaders();
        }
        var allHeaders = "";
        $( ["Cache-Control", "Content-Language", "Content-Type",
                "Expires", "Last-Modified", "Pragma"] ).each(function (i, header_name) {

            if ( xhr.getResponseHeader( header_name ) ) {
                allHeaders += header_name + ": " + xhr.getResponseHeader( header_name ) + "\n";
            }
            return allHeaders;
        });
    };
    return xhr;
};

Extending Ajax

jQuery 1.5부터, jQuery의 Ajax 는 더 유연하게 사용할 수 있도록 확장된 사전필터(prefilters), 컨버터(converters), 변환(transports)이 포함되어 있습니다. 이런 이점에 대해 더 많은 정보를 얻으시려면 Extending Ajax 페이지를 살펴 보십시오.

Additional Notes:

보안 문제로 인해 대부분의 "Ajax" 요청은 제한이 있습니다. 도메인, 서브 도메인, 프로토콜이 다른 상황에서의 조회는 사용하지 못합니다. Script 와 JSONP 요청은 이런 제약에서 자유롭습니다.

예 제  
서버에 데이터를 보내고 완료되면 사용자에게 알립니다.

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

 

예 제  
HTML 페이지의 최신 버전을 요청합니다.

$.ajax({
  url: "test.html",
  cache: false
}).done(function( html ) {
  $("#results").append(html);
});

 

예 제  
XML 데이터를 서버에 보냅니다. processData 옵션값을 false로 하여 자동으로 데이터가 string으로 변환되는 것을 방지합니다.

var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
  url: "page.php",
  processData: false,
  data: xmlDocument
});

xmlRequest.done(handleResponse);

 

예 제  
서버로 데이터를 보내고, 서버는 저장 후 특정 메시지를 보내 줍니다. 완료되면 로그 메시지를 갱신하고 실패하면 알림창을 나타냅니다.

var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  $("#log").html( msg );
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

 

예 제  
JavaScript 파일을 로드하고 실행합니다.

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

 

 

조금 쉬어가면서 작성했지만, 역시 역부족이네요. 사실 너무 길어서 필요한 것만 할까 생각했지만 그래도 처음부터 발번역을 했습니다. 나중에 개정판(?)이 될지는 모르겠지만 아마 고쳐야 할 부분이 너무 많습니다. 맨위에서 권고 드렸듯이 예제만 보는 것이 정신건강에 좋을 듯합니다. ^^;;;;;

그럼 즐프하세요.

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.

Posted by 1010
98..Etc/jQuery2014. 1. 9. 17:54
반응형

http://wwwendt.de/tech/dynatree/doc/dynatree-doc.html


Example: Standard jQuery drag-and-drop

This sample uses the standard jQuery draggable and droppable.

Skin: 

This tree allows dragging.

This tree allows dropping.

Active node: -Active node: -

Drag me around

Drop something here


Dynatree DEVELOPMENT, jQuery UI 1.8.24, jQuery 1.8.2

Dynatree documentation

This document describes dynatree version: $Version:$.
Document revision: $Revision:$.
A current version may be found at the project site http://wwwendt.de/tech/dynatree/index.html.

Dynatree is a dynamic JavaScript tree view control with support for checkboxes, drag'n'drop, and lazy loading.

Main features:

  • Open source (MIT and GPL License)
  • Optimized for large dynamic trees (DOM elements are only created when really needed).
  • Programmable through a rich object oriented interface.
  • Support for lazy loading and Ajax.
  • Checkboxes and hierarchical selection.
  • Supports drag and drop.
  • Support for persistence.
  • Keyboard aware.
  • Initializes from HTML code, JSON, or JavaScript objects.
  • Implemented as a jQuery plugin.
    (Note: this doesn't mean that you have to use jQuery for your whole site.)

Dynatree runs best, when the HTML document is rendered in a strict mode like
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
Avoid the quirks mode.

1 Download

You can download the current dynatree package at http://code.google.com/p/dynatree/downloads. It contains everything needed including the source, some documentation and examples.
jQuery is already included, but you can check the jQuery site for the latest versions of jquery.js and ui.core.js.

2 Examples

This documentation contains script examples and links.
See also the Example Browser for some more advanced live demos.

Using the [View source code] link in the Example Browser is probably the best way to learn about Dynatree.

3 Quick start

Let's start with a simple example:

Try this example...
<html>
<head>
   
<!-- Include the required JavaScript libraries: -->
   
<script src='jquery/jquery.js' type="text/javascript"></script>
   
<script src='jquery/jquery-ui.custom.js' type="text/javascript"></script>
   
<script src='jquery/jquery.cookie.js' type="text/javascript"></script>

   
<link rel='stylesheet' type='text/css' href='skin/ui.dynatree.css'>
   
<script src='jquery.dynatree.js' type="text/javascript"></script>

   
<!-- Add code to initialize the tree when the document is loaded: -->
   
<script type="text/javascript">
    $
(function(){
       
// Attach the dynatree widget to an existing <div id="tree"> element
       
// and pass the tree options as an argument to the dynatree() function:
        $
("#tree").dynatree({
            onActivate
: function(node) {
               
// A DynaTreeNode object is passed to the activation handler
               
// Note: we also get this event, if persistence is on, and the page is reloaded.
                alert
("You activated " + node.data.title);
           
},
            persist
: true,
            children
: [ // Pass an array of nodes.
               
{title: "Item 1"},
               
{title: "Folder 2", isFolder: true,
                    children
: [
                       
{title: "Sub-item 2.1"},
                       
{title: "Sub-item 2.2"}
                   
]
               
},
               
{title: "Item 3"}
           
]
       
});
   
});
   
</script>
</head>
<body>
   
<!-- Add a <div> element where the tree should appear: -->
   
<div id="tree"> </div>
</body>
</html>

As an alternative, it is possible to leave away the children option and add a <ul> inside the <div id="tree"> tag instead.
See Initializing the tree structure from a <ul> element for an example.

I am going into more details in the following sections.

4 Initializing the tree

Dynatree is based on and made for jQuery. If you are not familiar with this, you might also want to check the jQuery documentation.

The tree is initialized in the onload event of the html document. In jQuery this is usually done by passing a function to $(..) :

<head>
   
<script type="text/javascript">
        $
(function(){
           
[…]
       
});
   
</script>
</head>

The dynatree widget is then attached to an empty <div > element with a given ID of 'tree'. This id can have any value, it only has to match the jQuery selector, in our case '#tree'.
Options are passed to the dynatree() function as a dictionary in curly braces:

            $("#tree").dynatree({
               
[…]
           
});

4.1 Tree options

Tree options are passed as plain JavaScript objects in curly braces, e.g.
{ … }.

The following script shows the available options.
All options have a reasonable default, so we may only have to pass the onActivate handler.

$("#tree").dynatree({
    title
: "Dynatree", // Tree's name (only used for debug outpu)
    minExpandLevel
: 1, // 1: root node is not collapsible
    imagePath
: null, // Path to a folder containing icons. Defaults to 'skin/' subdirectory.
    children
: null, // Init tree structure from this object array.
    initId
: null, // Init tree structure from a <ul> element with this ID.
    initAjax
: null, // Ajax options used to initialize the tree strucuture.
    autoFocus
: true, // Set focus to first child, when expanding or lazy-loading.
    keyboard
: true, // Support keyboard navigation.
    persist
: false, // Persist expand-status to a cookie
    autoCollapse
: false, // Automatically collapse all siblings, when a node is expanded.
    clickFolderMode
: 3, // 1:activate, 2:expand, 3:activate and expand
    activeVisible
: true, // Make sure, active nodes are visible (expanded).
    checkbox
: false, // Show checkboxes.
    selectMode
: 2, // 1:single, 2:multi, 3:multi-hier
    fx
: null, // Animations, e.g. null or { height: "toggle", duration: 200 }
    noLink
: false, // Use <span> instead of <a> tags for all nodes
   
// Low level event handlers: onEvent(dtnode, event): return false, to stop default processing
    onClick
: null, // null: generate focus, expand, activate, select events.
    onDblClick
: null, // (No default actions.)
    onKeydown
: null, // null: generate keyboard navigation (focus, expand, activate).
    onKeypress
: null, // (No default actions.)
    onFocus
: null, // null: set focus to node.
    onBlur
: null, // null: remove focus from node.

   
// Pre-event handlers onQueryEvent(flag, dtnode): return false, to stop processing
    onQueryActivate
: null, // Callback(flag, dtnode) before a node is (de)activated.
    onQuerySelect
: null, // Callback(flag, dtnode) before a node is (de)selected.
    onQueryExpand
: null, // Callback(flag, dtnode) before a node is expanded/collpsed.

   
// High level event handlers
    onPostInit
: null, // Callback(isReloading, isError) when tree was (re)loaded.
    onActivate
: null, // Callback(dtnode) when a node is activated.
    onDeactivate
: null, // Callback(dtnode) when a node is deactivated.
    onSelect
: null, // Callback(flag, dtnode) when a node is (de)selected.
    onExpand
: null, // Callback(flag, dtnode) when a node is expanded/collapsed.
    onLazyRead
: null, // Callback(dtnode) when a lazy node is expanded for the first time.
    onCustomRender
: null, // Callback(dtnode) before a node is rendered. Return a HTML string to override.
    onCreate
: null, // Callback(dtnode, nodeSpan) after a node was rendered for the first time.
    onRender
: null, // Callback(dtnode, nodeSpan) after a node was rendered.
    postProcess
: null, // Callback(data, dataType) before an Ajax result is passed to dynatree.

   
// Drag'n'drop support
    dnd
: {
       
// Make tree nodes draggable:
        onDragStart
: null, // Callback(sourceNode), return true, to enable dnd
        onDragStop
: null, // Callback(sourceNode)
       
// Make tree nodes accept draggables
        autoExpandMS
: 1000, // Expand nodes after n milliseconds of hovering.
        preventVoidMoves
: true, // Prevent dropping nodes 'before self', etc.
        revert
: false, // true: slide helper back to source if drop is rejected
        onDragEnter
: null, // Callback(targetNode, sourceNode, ui, draggable)
        onDragOver
: null, // Callback(targetNode, sourceNode, hitMode)
        onDrop
: null, // Callback(targetNode, sourceNode, hitMode, ui, draggable)
        onDragLeave
: null // Callback(targetNode, sourceNode)
   
},
    ajaxDefaults
: { // Used by initAjax option
        cache
: false, // false: Append random '_' argument to the request url to prevent caching.
        timeout
: 0, // >0: Make sure we get an ajax error for invalid URLs
        dataType
: "json" // Expect json format and pass json object to callbacks.
   
},
    strings
: {
        loading
: "Loading…",
        loadError
: "Load error!"
   
},
    generateIds
: false, // Generate id attributes like <span id='dynatree-id-KEY'>
    idPrefix
: "dynatree-id-", // Used to generate node id's like <span id="dynatree-id-<key>">.
    keyPathSeparator
: "/", // Used by node.getKeyPath() and tree.loadKeyPath().
    cookieId
: "dynatree", // Choose a more unique name, to allow multiple trees.
    cookie
: {
        expires
: null // Days or Date; null: session cookie
   
},
   
// Class names used, when rendering the HTML markup.
   
// Note:
   
// These settings only apply on initialisation.
   
// If only single entries are passed for options.classNames, all other
   
// values are still set to default.
    classNames
: {
        container
: "dynatree-container",
        node
: "dynatree-node",
        folder
: "dynatree-folder",

        empty
: "dynatree-empty",
        vline
: "dynatree-vline",
        expander
: "dynatree-expander",
        connector
: "dynatree-connector",
        checkbox
: "dynatree-checkbox",
        nodeIcon
: "dynatree-icon",
        title
: "dynatree-title",
        noConnector
: "dynatree-no-connector",

        nodeError
: "dynatree-statusnode-error",
        nodeWait
: "dynatree-statusnode-wait",
        hidden
: "dynatree-hidden",
        combinedExpanderPrefix
: "dynatree-exp-",
        combinedIconPrefix
: "dynatree-ico-",
        hasChildren
: "dynatree-has-children",
        active
: "dynatree-active",
        selected
: "dynatree-selected",
        expanded
: "dynatree-expanded",
        lazy
: "dynatree-lazy",
        focused
: "dynatree-focused",
        partsel
: "dynatree-partsel",
        lastsib
: "dynatree-lastsib"
   
},
    debugLevel
: 1 // 0:quiet, 1:normal, 2:debug
});

Details:

opts.classNames
Type: dictionary, default: $.ui.dynatree.defaults.classNames.
Override class names, that are used, when rendering the HTML markup.
Typically this will require some customization of the CSS file too. 
Note: class names are applied on initialisation only. 
Example:
$("#tree1").dynatree({
    checkbox
: true,
   
// Override class name for checkbox icon:
    classNames
: {checkbox: "dynatree-radio"},
   
[...]
opts.clickFolderMode
Type: integer, default: 3.
Define, how a mouse click will change a folder status.
  1. Single-clicking a folder title (or pressing the [enter] or [space] key) will activate it.
    In this mode documents and folders behave the same.
  2. Single-clicking a folder title expands the node. The folder cannot be activated.
  3. Single-clicking a folder title will activate and expand it.
opts.persist
Type: boolean, default: false.
True: the tree's expansion, activation, focus and selection state is saved to a session cookie, so reloading the page will restore the status.
Notes: this may not work with lazy nodes.
See cookie option.

4.2 Initializing the tree structure

A tree structure is made of nodes. Every node may in turn contain a list child nodes.
A dynatree always has exactly one root node, and all top level nodes of our tree are created as direct descendants.
The root node is usually hidden, so we only see the nodes that we have added.

Dynatree can read it's structure from different sources:

  1. If the children option is passed, it will be used.
  2. Otherwise, if the initAjax option is passed, it will be used.
  3. Otherwise, if the initId option is passed, it will be used.
  4. Otherwise, if the the container <div> element contains a <ul> element, it will be used.
  5. Otherwise, the tree is left empty.
    But we may choose to do so, if we want to modify the tree programmatically.

Methods 1-3 expect a list of node options, as described in the following sections.

4.2.1 Node options

Node options are defined as plain JavaScript objects in curly braces, e.g.
{ … }.
Most of the time we pass a list of node options like this
children: [ { … }, { … }, … ].

The follwing snippet shows the attributes that can be used to define a tree node.
There are reasonable default values for all options, so we may only have to pass a title.

children: [
   
{
    title
: null, // (required) Displayed name of the node (html is allowed here)
    key
: null, // May be used with activate(), select(), find(), ...
    isFolder
: false, // Use a folder icon. Also the node is expandable but not selectable.
    isLazy
: false, // Call onLazyRead(), when the node is expanded for the first time to allow for delayed creation of children.
    tooltip
: null, // Show this popup text.
    href
: null, // Added to the generated <a> tag.
    icon
: null, // Use a custom image (filename relative to tree.options.imagePath). 'null' for default icon, 'false' for no icon.
    addClass
: null, // Class name added to the node's span tag.
    noLink
: false, // Use <span> instead of <a> tag for this node
    activate
: false, // Initial active status.
    focus
: false, // Initial focused status.
    expand
: false, // Initial expanded status.
   
select: false, // Initial selected status.
    hideCheckbox
: false, // Suppress checkbox display for this node.
    unselectable
: false, // Prevent selection.
   
// The following attributes are only valid if passed to some functions:
    children
: null // Array of child nodes.
   
// NOTE: we can also add custom attributes here.
   
// This may then also be used in the onActivate(), onSelect() or onLazyTree() callbacks.
   
},
   
[…]
]

The node options are also passed to the event handlers and can be accessed like this:

onActivate: function(node) {
    alert
("You activated " + node.data.title);
},

Details:

data.activate
If set to true, the node will be initially activated.
data.addClass
Class name that is added to the node's <span> element.
Example:
{ title: "Pretty node", addClass: "customClass1" }
or
<li data="addClass: 'customClass1'">Pretty node
can be styled using css as
span.customClass1 a { background-color: maroon; color: yellow; }
data.children
Array of node options, that are used to generate child nodes.
This option is only valid when passed to certain functions, like DynTreeNode.addChild().
data.expand
If set to true, the node will be initially expanded.
data.focus
If set to true, the node will be initially focused.
data.hideCheckbox
Suppress display of checkbox icon.
It is still possible to (de)select the node using the API, keyboard or initialization data. (The selection state may be visualized by a CSS style.)
See also unselectable.
data.href
Contains the link URL, if the tree was initialized from a <ul> tag:
<div id="tree"><ul>
   
<li class="expanded folder">Search engines
   
<ul>
       
<li><a href="http://www.google.com" target="_self">Google</a>
       
<li><a href="http://www.bing.com">Bing</a>
data.icon
Optional name of an image file relative to the image directory. 
If null specified, a default image is used depending on the node type (folder or document). This is the default.
If false specified, no image is displayed.
data.isFolder
Marks node as folder (treated as a document otherwise).
See Folders and Documents
data.isLazy
Enables delayed loading of the node contents. When a lazy node is expanded for the first time, the onLazyRead() callback is called.
data.key
Uniquely identifies this node. It is optional, but we need it for some functions like tree.activateKey().
If specified, the node's element id is generated by prepending a prefix like this: dynatree-id-1234.
If not specified, a random key id is generated.
data.select
If set to true, the node will be initially selected.
data.target
See data.href.
data.title
Type: string, default: "".
Displayed name of the node (html markup is allowed here).
data.tooltip
Optional string to display in a popup window when the cursor hovers over the node.
data.unselectable
Prevent (de)selection of this node using API, mouse, and keyboard.
It is still possible, to (de)select this node in the initialization data or indirectly (in multi-hier mode).
See also hideCheckbox.

To override the node attribute defaults, modify the structure before initializing dynatree:

<script type="text/javascript">
    $.ui.dynatree.nodedatadefaults["icon"] = false; // Turn off icons by default

    $(function(){
        $("#tree").dynatree({
            rootVisible: false,
            [...]

4.2.2 Folders and documents

When a node is of type folder, it get's a special folder icon and class name.
We usually use them to hold child nodes.
Also, folders can be expanded by clicking the title text (this behavior can be controlled using the clickFolderMode option).

Non-folders ('documents') may also contain child nodes.
Clicking on a child node activates it, so we have to click the small [+] icon in front to expand such a document node.

4.2.3 Initializing the tree structure from an object array

In the quick example above we have already seen how a tree is initialized by passing a node array with the children option.

$("#tree").dynatree({
    children
: [ ],
   
[…]
});

See also Node options.

4.2.4 Initializing the tree structure from an Ajax response

Instead of passing an array of data objects, we can pass a url in the initAjax option that will be used to contact an Ajax web service.

$("#tree").dynatree({
    initAjax
: {url: "/ajaxTree",
               data
: {key: "root", // Optional arguments to append to the url
                      mode
: "all"
                     
}
               
},
   
[…]
});

The web service is expected to return a valid JSON node list, formatted like this:
[ { ... }, { ... }, ... ].

Because the data request is performed asynchronously, the document will load faster. Dynatree will display a spinning wheel, while waiting for the request to complete.

See Loading child nodes on demand for details.
See Persistence for lazy trees for a sample on how to combine this with persistence.

4.2.5 Initializing the tree structure from a <ul> element

If the container <div> contains a <ul> element, the node titles are read from the <li> tags.
If the title contains html markup, it may be better to wrap it inside a span element.

All other node options are specified in the data attribute of a <li> element. For example

<li data="url: 'http://jquery.com'">jQuery home
<li data="url: 'http://example.com', addClass: 'customClass1'">Example page

Note that the data attribute is not valid in <li> elements in some doctypes (HTML 4.01 transitional and Strict and XHTML 1.0 Strict). Validators will complain about this.
Also, if the id attribute is used to pass a key, it should be alphanumeric and start with a letter to be compliant.
(This doesn't seem to affect the functionality however.)

Nested <ul> elements are used to build a hierarchical tree structure.
After the <ul> element was parsed, it is removed from the DOM tree.

Note that <a> elements are recognized:
<li><a href='URL' target='TARGET'>TITLE</a> will result in
node.data.title = TITLE
node.data.href = URL
node.data.target = TARGET

Try this example...
<head>
   
<!-- Include the required JavaScript libraries: -->
   
<script src='jquery/jquery.js' type="text/javascript"></script>
   
<script src='jquery/jquery-ui.custom.js' type="text/javascript"></script>

   
<link rel='stylesheet' type='text/css' href='skin/ui.dynatree.css' >
   
<script src='jquery.dynatree.js' type="text/javascript"></script>

   
<!-- Add code to initialize the tree when the document is loaded: -->
   
<script type="text/javascript">
    $
(function(){
        $
("#tree").dynatree({
            onActivate
: function(node) {
                alert
("You activated " + node);
           
}
       
});
   
});
   
</script>
</head>
<body>
   
<!-- Add a <div> element where the tree should appear: -->
   
<div id="tree">
       
<ul>
           
<li id="key1" title="Look, a tool tip!">item1 with key and tooltip
           
<li id="key2" class="selected">item2: selected on init
           
<li id="key3" class="folder">Folder with some children
               
<ul>
                   
<li id="key3.1">Sub-item 3.1
                   
<li id="key3.2">Sub-item 3.2
               
</ul>

           
<li id="key4" class="expanded">Document with some children (expanded on init)
               
<ul>
                   
<li id="key4.1">Sub-item 4.1
                   
<li id="key4.2">Sub-item 4.2
               
</ul>

           
<li id="key5" class="lazy folder">Lazy folder
       
</ul>
   
</div>
</body>

4.2.6 Initializing the tree structure programmatically

Finally, it is always possible to program the DynaTree and DynaTreeNode objects directly.

See also Programming dynatree.

Try this example...
$(function(){
   
// Initialize the tree in the onload event
    $
("#tree").dynatree({
        onActivate
: function(node) {
            alert
("You activated " + node);
       
}
   
});
   
// Now get the root node object
   
var rootNode = $("#tree").dynatree("getRoot");
   
// Call the DynaTreeNode.addChild() member function and pass options for the new node
   
var childNode = rootNode.addChild({
        title
: "Child node 1",
        tooltip
: "This child node was added programmatically.",
        isFolder
: true
   
});
   
//
    childNode
.addChild({
        title
: "Document using a custom icon",
        icon
: "customdoc1.gif"
   
});
});

5 Handling events

When a user clicks a node, we want to react in some way. So at least we want to implement an onActivate handler.

All event handlers are passed an instance of DynaTreeNode as argument.
this refers to the Dynatree object.
The node options can be accessed like this:

onActivate: function(node) {
    alert
("You activated " + node.data.title);
},

See also Programming dynatree.

5.1 DynaTree callbacks

The this context is set to the tree object.
Use tree.isUserEvent()tree.isInitializing(), and tree.isReloading() to determine who generated this event.

opts.onActivate(node)
Called when a node was activated.
onActivate: function(node) {
   
if(node.tree.isUserEvent()){
       
[...] // Do something after user activated the node (using mouse or keyboard)
   
}
}
opts.onBlur(node)
Called when a node lost the focus.
opts.onClick(node, event)
Called when a node was clicked.
Use node.getEventTargetType(event) to check which area was clicked.
Return false to prevent default processing (setting focus, activate the node, expand folders, etc.).
onClick: function(node, event) {
   
if(node.getEventTargetType(event) == "title"){
       
[...] // Handle the click event
       
return false;// Prevent default processing
   
}
}
opts.onCreate(node, nodeSpan)
Called after a node's HTML tag was created, i.e. when a node becomes visible for the first time.
This callback may be used to bind events or widgets for nodes that are created lazily or programatically.
onCreate: function(node, nodeSpan) {
    $
(span).click(function(e){
        alert
('clicked ' + node);
   
});
}
(Note that the use of jQuery live events may often be a more efficient solution.)
See also opts.onRender.
opts.onCustomRender(node)
Called before a node's title HTML tag will be created. This happens when a node becomes visible for the first time.
This callback may return a string that will be used instead of the default HTML markup.
onCustomRender: function(node) {
   
return "<span class='dynatree-title'>SPAM</span>"
}
opts.onDblClick(node, event)
Called when a node was double clicked.
Use node.getEventTargetType(event) to check which area was clicked.
Return false to prevent default processing (currently none).
opts.onDeactivate(node)
Called when a node was deactivated.
opts.onExpand(flag, node)
Called when a node was expanded/collapsed.
opts.onFocus(node)
Called when a node receives the focus.
opts.onKeydown(node, event)
Called on keydown events.
Return false to prevent default processing (generate keyboard navigation, focus, expand, activate, etc.).
opts.onKeypress(node, event)
Called on keypress events.
Return false to prevent default processing (currently none).
opts.onLazyRead(node)
Called when a lazy node is expanded for the first time.
opts.onPostInit(isReloading, isError [, XMLHttpRequest, textStatus, errorThrown])
Called when the tree was (re)loaded.
In case of an error, isError will be true and addition info is passed: XMLHttpRequest, textStatus, errorThrown.
opts.onQueryActivate(flag, node)
Called before a node is (de)activated. Return false to prevent this.
opts.onQueryExpand(flag, node)
Called before a node is expanded/collapsed. Return false to prevent this.
opts.onQuerySelect(flag, node)
Called before a node is (de)selected. Return false to prevent this.
opts.onRender(node, nodeSpan)
Called after every time a node's HTML tag was created or changed.
This callback may be used to modify the HTML markup.
onRender: function(node, nodeSpan) {
    $
(nodeSpan).find("a.dynatree-title").css("color", "red");
}
See also opts.onCreate.
opts.onSelect(flag, node)
Called when a node was (de)selected.
opts.dnd.onDragStart(sourceNode)
This function must be defined to enable dragging for the tree. Return false to cancel dragging of node.
opts.dnd.onDragEnter(targetNode, sourceNode, ui, draggable)
Return true to make tree nodes accept dropping of draggables.
opts.dnd.onDragOver(targetNode, sourceNode, hitMode, ui, draggable)
opts.dnd.onDragLeave(targetNode, sourceNode, ui, draggable)
opts.dnd.onDrop(targetNode, sourceNode, hitMode, ui, draggable)
This function must be defined to enable dropping of items on the tree.
opts.dnd.onDragStop(sourceNode)
ajaxOptions.success(node)
(Passed as argument to node.appendAjax(...).)
Called after nodes have been created and the waiting icon was removed. 'this' is the options for this Ajax request
ajaxOptions.error(node, XMLHttpRequest, textStatus, errorThrown)
(Passed as argument to node.appendAjax(...).)

5.2 Handling activate/click

The following example handles an activation event by opening a url in a new window.
This assumes, that we have defined an additional custom attribute named 'url' in the node options, like so:

<ul>
   
<li data="url: 'http://jquery.com'">jQuery home
   
<li data="url: 'http://docs.jquery.com'">jQuery docs

or

children: [
   
{ title: "jQuery home", url: "http://jquery.com" },
   
{ title: "jQuery docs", url: "http://docs.jquery.com" },

Also, the title of the currently active node is displayed in the <span id='echoActive'> tag.

Try this example...
$("#tree").dynatree({
   
[…]
    onActivate
: function(node) {
       
if( node.data.url )
            window
.open(node.data.url);
        $
("#echoActive").text(node.data.title);
   
},
    onDeactivate
: function(node) {
        $
("#echoActive").text("-");
   
},
   
[…]
});

5.3 Handling selection events

The following example writes the title of the currently focused node to the <span id='echoFocused'> element:

Try this example...
    $("#tree").dynatree({
       
[…]
        onSelect
: function(flag, node) {
           
if( ! flag )
                alert
("You deselected node with title " + node.data.title);
           
var selectedNodes = node.tree.getSelectedNodes();
           
var selectedKeys = $.map(selectedNodes, function(node){
               
return node.data.key;
           
});
            alert
("Selected keys: " + selectedKeys.join(", "));
       
},
       
[…]
   
});
   

5.4 Handling focus changes

If we use the cursor keys to walk the tree nodes, the focus changes to the next node, but the active node remains the same unless we use [Space] or [Enter].
Also, when we click on a folder node it is only focused, but not activated.

The following example writes the title of the currently focused node to the <span id='echoFocused'> element:

Try this example...
$("#tree").dynatree({
   
[…]
    onFocus
: function(node) {
        $
("#echoFocused").text(node.data.title);
   
},
    onBlur
: function(node) {
        $
("#echoFocused").text("-");
   
},
   
[…]
});

5.5 Loading child nodes on demand ('lazy loading')

Dynatree supports delayed loading of tree nodes, which means we read the child nodes only when their parent is expanded.

Because the data request is performed asynchronously, the browser will not block and is still responsive. Dynatree will display a spinning wheel, while waiting for the request to complete.

To make this happen, we have to

  • Mark some or all nodes as lazy, by setting the isLazy option to true.
  • Implement a backend web service that delivers a JSON formatted node list.
  • Implement the onLazyRead callback to send an Ajax request, create the child nodes, and set the 'ok' status.
Try this example...
$("#tree").dynatree({
   
[…]
    onLazyRead
: function(node){
        node
.appendAjax({url: "/sendData",
                           data
: {"key": node.data.key, // Optional url arguments
                                 
"mode": "all"
                                 
}
                         
});
   
},
   
[…]
});

Typically we would implement onLazyRead by calling the node.appendAjax() function.
It expects one option object argument, as described in the documentation for the jQuery.ajax() command.

These options are set by default:
cache: false and dataType: "json".

Note that the success and error options are implemented differently from the jQuery standard:
They pass different arguments and are called after the Dynatree default processing took place.
This makes it easy to use the success callback to apply any custom postprocessing, for example activating a node or binding events.

$("#tree").dynatree({
   
[…]
    onLazyRead
: function(node){
        node
.appendAjax({url: "/sendData",
                           data
: {"key": node.data.key, // Optional url arguments
                                 
"mode": "all"
                                 
},
                           
// (Optional) use JSONP to allow cross-site-requests
                           
// (must be supported by the server):
//                         dataType: "jsonp",
                           success
: function(node) {
                               
// Called after nodes have been created and the waiting icon was removed.
                               
// 'this' is the options for this Ajax request
                               
},
                           error
: function(node, XMLHttpRequest, textStatus, errorThrown) {
                               
// Called on error, after error icon was created.
                               
},
                           cache
: false // Append random '_' argument to url to prevent caching.
                         
});
   
},
   
[…]
});

The web service is expected to return a valid JSON node list, formatted like this:
[ { "title": "Node1", "isLazy": true, "key": "BC13B21636CD6D5C", … }, { … }, … ]
See Node options for a list of supported attributes.

When the response was received, appendAjax() appends the child nodes and calls node.setLazyNodeStatus(DTNodeStatus_Ok) to remove the wait icon.

Note that initAjax is simply a special case, where the tree's root node is loaded on startup.
See Initializing the structure from an Ajax response for a sample to initialize the whole tree with an Ajax request.

This sample code (written in Python) shows how a server could create a response:

# Build node list as JSON formatted string:
res
= '['
res
+= '{ "title": "Node 1", "key": "k1", "isLazy": true },'
res
+= '{ "title": "Node 2", "key": "k2", "isLazy": true },'
res
+= '{ "title": "Node 3", "key": "k3", "isLazy": true }' # no trailing "," at the last line
res
+= ']'

# Add support for the JSONP protocol:
# This means, if the request URL contains an argument '?callback=xxx',
# wrap the result as 'xxx(result)'
if "callback" in argDict:
    res
= argDict["callback"] + "(" + res + ")"

# Make sure, content type is JSON:
start_response
("200 OK", [("Content-Type", "application/json")])

# Return result (the square brackets are Python / WSGI specific):
return [ res ]

See dynatree_server.py for a sample implementation of a web server that handles this (~150 lines of Python code).
When this server is running, you can try this live example of a lazy tree.

5.5.1 Loading custom formats

If we need more control, or if the server cannot provide JSON in Dynatree's native format, we could also use jQuery.ajax() to fetch the data, then transform it and callnode.addChild():

$("#tree").dynatree({
   
[…]
    onLazyRead
: function(node){
        $
.ajax({
            url
: […],
            success
: function(data, textStatus){
               
// In this sample we assume that the server returns JSON like
               
// { "status": "...", "result": [ {...}, {...}, ...]}
               
if(data.status == "ok"){
                   
// Convert the response to a native Dynatree JavaScipt object.
                   
var list = data.result;
                    res
= [];
                   
for(var i=0, l=list.length; i<l; i++){
                       
var e = list[i];
                        res
.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
                            icon
: false});
                   
}
                   
// PWS status OK
                    node
.setLazyNodeStatus(DTNodeStatus_Ok);
                    node
.addChild(res);
               
}else{
                   
// Server returned an error condition: set node status accordingly
                    node
.setLazyNodeStatus(DTNodeStatus_Error, {
                        tooltip
: data.faultDetails,
                        info
: data.faultString
                   
});
               
}
           
}
       
});
   
[…]
});

6 Drag'n'drop

Drag and drop functionality is enabled by defining the appropriate callbacks:

    $("#tree").dynatree({
       
[...]
        dnd
: {
            onDragStart
: function(node) {
               
/** This function MUST be defined to enable dragging for the tree.
                 *  Return false to cancel dragging of node.
                 */

                logMsg
("tree.onDragStart(%o)", node);
               
return true;
           
},
            onDrop
: function(node, sourceNode, hitMode, ui, draggable) {
               
/** This function MUST be defined to enable dropping of items on
                 * the tree.
                 */

                logMsg
("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode);
                sourceNode
.move(node, hitMode);
           
}
       
}
   
});

There are a lot more callbacks that can be used to fine tune the behaviour. Check the source code in the samples in the Example Browser to learn more.

7 Persistence

When initializing a tree in persist mode, we first check, if persistence cookies already exist.
If not, we assume first-time initializing, read the status from the tree source, and store it into new cookies.

Otherwise we assume re-loading, ignore the source node attributes and override them using the cookie info.

In either case, the 'active', 'expand' and 'select' status of a node is read from the data or restored from the cookies.
However, no onQueryActivate, onActivate, onExpand, onSelect, etc. events are fired. (The only event that may be fired is onFocus.)
In order to generate these events on reload, we may use the callback function onPostInit() and tree.reactivate().

$("#tree").dynatree({
   
[…]
    onPostInit
: function(isReloading, isError) {
       
// 'this' is the current tree
       
// isReloading is true, if status was read from existing cookies
       
// isError is only used in Ajax mode
       
// Fire an onActivate() event for the currently active node
       
this.reactivate();
   
},
    onActivate
: function(node) {
       
// Use status functions to find out about the calling context
       
var isInitializing = node.tree.isInitializing(); // Tree loading phase
       
var isReloading = node.tree.isReloading(); // Loading phase, and reading status from cookies
       
var isUserEvent = node.tree.isUserEvent(); // Event was triggered by mouse or keyboard

        $
("#echoActive").text(node.data.title);
   
},

7.1 Persistence for lazy trees

The problem with restoring the status of a lazy tree is, that the currently active or selected nodes may not be part of the tree, when it is freshly re-loaded.

The basic idea is to leave it up to the backend web service to deliver not only the top-level nodes, but also all nodes that are required to display the current status.

For example, it may be neccessary to render 3 parent nodes, if the active node is at level # 4.
The backend may also deliver all child nodes of expanded parents.
Or in selectMode 3 (hierarchical) we may want to send all nodes, that are partly selected.

initAjax (and appendAjax) have 3 options, that make it easy to pass persistence information to the web service.

See dynatree_server.py for a sample implementation of a web server that handles this (~150 lines of Python code).
When this server is running, you can try this live example of a lazy tree.

$("#tree").dynatree({
   
[…]
    initAjax
: {url: "/ajaxTree",
               data
: {key: key,
                      mode
: mode,
                      filter
: filter
                     
},
               addActiveKey
: true,  // add &activeKey= parameter to URL
               addFocusedKey
: true, // add &focusedKey= parameter to URL
               addExpandedKeyList
: true // add &expandedKeyList= parameter to URL
               
},
    onPostInit
: function(isReloading, isError) {
       
// In lazy mode, this will be called *after* the initAjax request returned.
       
// 'this' is the current tree
       
// isReloading is set, if status was read from existing cookies
       
// isError is set, if Ajax failed
       
// Fire an onActivate() event for the currently active node
       
this.reactivate();
   
},
    onActivate
: function(node) {
       
// Use status functions to find out about the calling context
       
var isUserEvent = node.tree.isUserEvent(); // Event was triggered by mouse or keyboard

        $
("#echoActive").text(node.data.title);
   
},

8 Programming dynatree

The dynatree widget provides a set of plugin methods, that can be called directly.
For example

$("#tree").dynatree("disable");

However this plugin implementation is based on a class called DynaTree that holds a set of DynaTreeNode objects.
These classes expose methods that can be accessed for enhanced functionality.
For example:

// Get the DynaTree object instance:
var tree = $("#tree").dynatree("getTree");
// Use it's class methods:
tree
.activateKey("key1234");
// Get a DynaTreeNode object instance:
var node = tree.getNodeByKey("key7654");
var rootNode = $("#tree").dynatree("getRoot");
// and use it
node
.toggleExpand();

8.1 Dynatree Plugin methods

Besides the constructor, that is called like this:

$("#tree").dynatree({
   
[…]
});

The following methods are globally available from the ui.dynatree namespace:

$.ui.dynatree.getNode(el)
Return a DynaTreeNode object for a given DOM element.
`el` may be a DOM element or a jQuery object. Example:
$("#tree a").hover(function(){
       
var node = $.ui.dynatree.getNode(this);
        logMsg
("Hover in %s", node);
   
}, function(){
       
[...]
   
});
$.ui.dynatree.getPersistData(cookieId, cookieOpts)
Return cookie persistence info as dictionary.
$.ui.dynatree.version
Release version number.

The following methods are directly available from the plugin:

$("#tree").dynatree("disable")
Disable event handling and add a class 'dynatree-disabled' to the container element.
$("#tree").dynatree("enable")
Enable event handling and remove the 'dynatree-disabled' class from the container element.
$("#tree").dynatree("option", )
Set a dynatree option at runtime. Example:
$("#tree").dynatree("option", "autoCollapse", true);
$
("#tree").dynatree("option", "fx", { height: "toggle", duration: 200 });
$("#tree").dynatree("getTree")
Return the associated DynaTree object.
$("#tree").dynatree("getRoot")
Return the root DynaTreeNode object of the tree.
$("#tree").dynatree("getActiveNode")
Return the DynaTreeNode object that is currently active.
(May be null.)
$("#tree").dynatree("getSelectedNodes")
Return an array of DynaTreeNode objects that are currently selected.
(May be empty: [ ].)

8.2 DynaTree class members

tree.activateKey(key)
Activate and focus node with a given key and fire focus and activate events.
If activeVisible option is set, all parents will be expanded as necessary.
If key is null, the current activation is removed.
Return the active DynaTreeNode.
tree.count()
Return the number of nodes.
tree.disable()
Disable input for the tree and display gray. This is a shortcut for $("#tree").dynatreee("disable").
tree.enable()
Complement to tree.disable().
tree.enableUpdate(enable)
Turn rendering on or off and return the previous mode. Disabling update may speedup processing, when adding lots of nodes.
Don't forget to turn rendering back on, after applying the changes:
var prevMode = tree.enableUpdate(false);
[...]
tree
.enableUpdate(prevMode);
tree.getActiveNode()
Return the currently active DynaTreeNode or null.
tree.getNodeByKey(key)
Return DynaTreeNode with a given key or 'null' if not found.
tree.getPersistData()
Return cookie persistence info as dictionary.
There is also a global function available: $.ui.dynatree.getPersistData(cookieId, cookieOpts).
tree.getRoot()
Return the invisible root DynaTreeNode object. All visible toplevel nodes are children of this system node.
tree.getSelectedNodes(stopOnParents)
Return a list of currently selected DynaTreeNodes (may be an empty array).
If stopOnParents is set to true, children of selected nodes are skipped. This may be convenient in selectMode:3 (multi-hier).
tree.initialize()
Constructor (internal use).
tree.isInitializing()
Return true, if the tree is in the init phase.
Use this function in an event handler, to check if the event was fired during a page reload, when the cookie persistence is applied.
tree.isReloading()
Return true, if the tree is in the init phase and persistence is on, and the current status was read from existing cookies.
Use this function in an event handler, to check if the event was fired during a page reload, when the cookie persistence is applied.
tree.isUserEvent()
Return true, if the tree is processing a user event.
Use this function in an event handler, to check if the event was fired in response to a mouse click or key stroke.
Otherwise, the the event was generated by an API call or during initialization.
tree.loadKeyPath(keyPath, callback)
Make sure that a node with a given ID is loaded, by traversing - and loading - its parents. This method is ment for lazy hierarchies.
A callback is executed for every node as we go.
tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
   
if(status == "loaded") {
       
// 'node' is a parent that was just traversed.
       
// If we call expand() here, then all nodes will be expanded
       
// as we go
        node
.expand();
   
}else if(status == "ok") {
       
// 'node' is the end node of our path.
       
// If we call activate() or makeVisible() here, then the
       
// whole branch will be exoanded now
        node
.activate();
   
}else if(status == "notfound") {
       
var seg = arguments[2],
            isEndNode
= arguments[3];
   
}
});
tree.logDebug(msg), logInfo(msg), logWarning(msg)
(Internal use).
tree.reactivate(setFocus)
Fire onQueryActivate and onActivate events for the currently active node (if there is one).
This may be useful when processing an onPostInit callback.
tree.redraw()
Render all visible nodes. See node.render() for details.
tree.reload()
Reload the the tree.
For lazy trees this is done, by re-submitting the Ajax request that was defined in the initAjax option.
This will not work, if the tree was loaded from an embedded <UL> element, because these elements are removed after they have been rendered.
tree.renderInvisibleNodes()
Force immediate HTML creation for all nodes, even if inside collapsed branches. This may be useful, if we want to bind events or otherwise must access these HTML elements.
It will however degrade performance, especially on large trees!
See node.render() for details.
tree.selectKey(key, flag)
Select or deselect node with a given key and fire focus and select events.
Return the selected DynaTreeNode.
tree.serializeArray(stopOnParents)
Return selected nodes as array of {name: 'TreeName', value: 'NodeKey'} objects, where name is the 'name' attribute of the tree's <div> element.
This format is compatible with jQuery's serializeArray() function and may be used in $.post() calls.
See also the 'form' sample in the Example Browser.
tree.toDict(includeRoot)
Convert the tree into a JavaScript object.
If 'includeRoot' is false or omitted, the result is an array of node dcts.
See node.toDict() for details.
tree.visit(fn, includeRoot)
Call fn(node) for all nodes.
Stop iteration, if fn() returns false. Stop iteration of the current branch, if fn() returns 'skip'.

8.3 DynaTreeNode class members

Attribute 'data'
Use this attribute to access all node options that were passed to create this node.
For example node.data.title or node.data.tooltip. See also Node options.
node.activate()
Activate this node - according to flag - and fire a onActivate event.
If activeVisible option is set, all parents will be expanded as necessary.
Focus is not set.
node.activateSilently()
Same as activate(), but does not fire events.
node.addChild(nodeData[, beforeNode])
Append a new child node.
nodeData may be a node data object as defined in Node options, or an array thereof. Also objects and arrays of type DynaTreeNode are allowed.
Example:
var node = $("#tree").dynatree("getTree").getNodeByKey("1234");
node
.addChild({title: "New Node", key: "3333"});
Since the nodeData may be a nested data structure, it is possible to create a deep hierarchy with one call.
The optional argument beforeNode specifies a child DynaTreeNode that the new node will be inserted before. (If this parameter is null or omitted, the new node will be appended.)
node.appendAjax(ajaxOptions)
Accepts a standard jQuery Ajax option object.
An asynchronous request is started, so this function returns immediately. While loading, a spinning wheel is displayed. On error, a red icon is shown.
The request handler must return a JSON object, formatted like the data's children object.
Use the setLazyNodeStatus() function to display the result.
See Loading child nodes on demand ('lazy loading') for details.
node.countChildren()
Return the number of descendant nodes, i.e. direct and indirect children.
node.deactivate()
Deactivate this node and fire an onDeactivate event.
node.expand(flag)
Expand or collapse this node - according to flag.
node.focus()
Set focus to this node. Parent nodes are expanded, if this is necessary to make it visible.
node.getChildren()
Return list of child nodes or null.
For lazy nodes that have not yet been loaded, undefined is is returned.
node.getEventTargetType(event)
Return the part of a node, that a click event occurred on.
Possible values: 'prefix' 'expander', 'checkbox', 'icon', 'title'.
null is returned else.
Note: there is no check, if the event was fired on this node.
node.getLevel()
Return the depth (i.e. number of parent nodes).
0 is returned for the root node.
node.getNextSibling()
Return the successor node or null.
node.getParent()
Return the parent node or null.
node.getPrevSibling()
Return the predecessor node or null.
node.hasChildren()
Return true if node has child nodes.
Return false if node is a leaf, i.e. has no child nodes.
Return undefined if this is a lazy node, that was not yet successfully loaded.
A test for 'node is surely empty' would be coded like
if(node.hasChildren() === false) ...
node.isActive()
Return true, if this node is activated. Only one tree node may be active at any time.
node.isChildOf(otherNode)
Return true, if this node is a direct child of otherNode.
node.isDescendantOf(otherNode)
Return true, if this node is a descendent (direct or indirect child) of otherNode.
node.isExpanded()
Return true, if the node is expanded.
node.isFirstSibling()
Return true, if this node is the first of all children of the current parent.
node.isFocused()
Return true, if this node is has the focus.
node.isLastSibling()
Return true, if this node is the last of all children of the current parent.
node.isLazy()
Return true, if the node is lazy (loaded or not).
node.isLoading()
Return true, if the node is lazy and currently loading (i.e. an Ajax request is active).
node.isSelected()
Return true, if the node is selected.
node.isStatusNode()
Return true, if this is an temporary status node. Status nodes are created while loading lazy data, to display a throbber or error condition.
node.isVisible()
Return true, if the node is visible, i.e. all parents are expanded.
node.makeVisible()
Expand all parents as neccessary, to make this node visible.
node.move(targetNode, mode)
Move this node to targetNode. Possible mode:
  • child: append this node as last child of targetNode. This is the default. To be compatble with the D'n'd hitMode, we also accept 'over'.
  • before: add this node as sibling before targetNode.
  • after: add this node as sibling after targetNode.
node.reload(force)
Deprecated. Use reloadChildren() instead.
node.reloadChildren(callback)
Discard and reload all children of a lazy node by triggering the onLazyRead event. if callback is passed, it is called after the Ajax request was executed. Example
node.reloadChildren(function(node, isOk){
   
if(!isOk) alert("Node " + node + " could not be reloaded.");
});
node.remove()
Remove this node and descendents from tree.
node.removeChildren()
Remove all child nodes and descendents.
node.render(useEffects, includeInvisible)
Redraw this node with current attributes. All HTML markup is updated and class names are added according to current status.
If this node is expanded, markup for children is recursively generated as well.
  • useEffects:
    (default: false) Set to false to prevent animated expand effects, which would be applied asynchronously.
  • includeInvisible:
    (default: false) Force HTML creation for all descendants, even if inside a collapsed branch.
    This may be useful, if we want to bind events or otherwise access these HTML elements. It will however degrade performance, especially on large trees.

Most of the time, there is no need to call this explicitly, since it is internally called on state changes.
node.resetLazy()
Remove all children from a lazy node and make sure it is collapsed. The node will be re-loaded when expanded the next time.
node.scheduleAction(mode, ms)
Schedule a delayed action. Possible mode:
  • expand: Expand this node after ms microseconds.
  • activate: Activate this node after ms microseconds.
  • cancel: cancel pending action, if any was scheduled.
node.select(flag)
Select or deselect this node - according to flag - and fire an onSelect event.
node.setLazyNodeStatus(status)
Display a dummy child node, to provide feedback, when loading a lazy node's content. 
Possible status:
  • DTNodeStatus_Loading: show a spinning wheel, with 'loading...' message.
  • DTNodeStatus_Error: show an error icon and message.
  • DTNodeStatus_Ok: Remove the status node.
Messages may be customized using the strings.loading and strings.loadError options.
node.setTitle(title)
Change current node title and redraw.
node.sortChildren(cmp, deep)
Sort child list by title.
cmd: optional compare function. If ommitted sorting is done by node titles.
deep: optional: pass true to sort all descendant nodes.
Example
// Custom compare function (optional) that sorts case insensitive
var cmp = function(a, b) {
    a
= a.data.title.toLowerCase();
    b
= b.data.title.toLowerCase();
   
return a > b ? 1 : a < b ? -1 : 0;
};
node
.sortChildren(cmp, false);
node.toDict(recursive, callback)
Convert the node into a JavaScript object.
recursive: set to true, to include child nodes.
callback: (optional) function to allow modifications.
Example
var cb = node.toDict(true, function(dict){
    dict
.title = "Copy of " + dict.title;
   
delete dict.key; // prevent duplicate keys
});
node.toggleExpand()
Toggle expansion state.
Expanding a lazy node, fires a onLazyRead event.
node.toggleSelect()
Toggle selection state.
node.visit(fn, includeSelf)
Call fn(node) for all child nodes.
Stop iteration, if fn() returns false. Stop iteration of the current branch, if fn() returns the string 'skip'.
node.visitParents(fn, includeSelf)
Call fn(node) for all parent nodes.
Stop iteration, if fn(node) returns false.

8.4 Programming examples

The follwing code snippets should give an idea on how to use the API.

8.4.1 Example: Select a node with key '1234'

$("#tree").dynatree("getTree").selectKey("1234");
// or another way:
$
("#tree").dynatree("getTree").getNodeByKey("1234").select();
// .. or yet another way (if 'generateIds' option was enabled):
$
("#dynatree-id-1234").prop("dtnode").select();

8.4.2 Example: Access the currently active node

var node = $("#tree").dynatree("getActiveNode");
if( node ){
    alert
("Currently active: " + node.data.title);
}

8.4.3 Example: Retrieve a node using for a DOM element or jQuery object

$(".dynatree-partsel").each(function(){
   
var node = $.ui.dynatree.getNode(this);
   
[...]
});

8.4.4 Example: Rename the active node

var node = $("#tree").dynatree("getActiveNode");
node
.data.title = "My new title";
node
.render();

8.4.5 Example: Add a child to the active node

var node = $("#tree").dynatree("getActiveNode");
var childNode = node.addChild({
    title
: "My new node",
    tooltip
: "This folder and all child nodes were added programmatically."
});

Note: instead of passing a single child object, we could also pass an array of such objects.
Also, the children may again contain children attributes, thus defining a sub tree.

8.4.6 Example: Add a hover handler and find the hovered node from any sub element

// Bind hover events to the tree's <a> tags:
$
("#tree a").hover(function(){
       
var node = $.ui.dynatree.getNode(this);
        logMsg
("Hover in %s", node);
   
}, function(){
       
var node = $.ui.dynatree.getNode(this);
        logMsg
("Hover out %s", node);
   
});

8.4.7 Example: Expand all nodes

$("#tree").dynatree("getRoot").visit(function(node){
    node
.expand(true);
});

8.4.8 Example: Save current tree status to the backend

// Get a JavaScript object copy of the tree
var dict = $("#tree").dynatree("getTree").toDict();
// ... then use Ajax to send this to your server...

8.4.9 Example: activate a node depending on URL

This sample shows how to parse the page URL and activate a node accordingly: http://server/_test-194.html?activate=_11

// Add a helper function to parse the URL
function getURLParameter(name) {
   
return unescape(
       
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
   
);
}
// Evaluate the URL after the tree was loaded
$
(function(){
    $
("#tree").dynatree({
       
[...]
        onPostInit
: function(isReloading, isError) {
           
var key = getURLParameter("activate");
           
if( key ) {
               
this.activateKey(key);
           
}
       
},

9 Theming and translation

The tree's fonts, colors, and icons are defined using CSS, so changing the appearance is simply a matter of including a custom stylesheet or by replacing icons.gif with another version.

Try this example...
<script src="../jquery/jquery.js" type="text/javascript"></script>
<script src="../jquery/jquery-ui.custom.js" type="text/javascript"></script>
<script src="../src/jquery.dynatree.js" type="text/javascript"></script>
<!-- Include the basic stylesheet: -->
<link href="../src/skin-vista/ui.dynatree.css" rel="stylesheet" type="text/css">
<!-- Override CSS with a custom stylesheet : -->
<link href="skin-custom/custom.css" rel="stylesheet" type="text/css" >

<script type="text/javascript">
    $
(function(){
        $
("#tree").dynatree({
           
[…]
       
});
   
});
</script>

Custom.css would include lines like this:

.dynatree-has-children span.dynatree-icon
{
    background
-position: 0 0;
    background
-image: url("doc_with_children.gif");
}

Changing the appearance and icons of single nodes is done by assigning a custom class:

<ul>
   
<li data="addClass: 'custom1'">Document with custom class

or

children: [
   
{ title: "Document with custom class", addClass: "custom1" },

we would then add CSS definitions for the new node to our stylesheet:

span.custom1 a
{
    background
-color: #ffffbb;
    color
: maroon;
}
span
.custom1 span.dynatree-icon
{
    background
-position: 0 0;
    background
-image: url("customDoc2.gif");
}

9.1 Translation

Strings can be translated in the tree options:

$("#tree").dynatree({
   
[…]
    strings
: {
        loading
: "Daten werden geladen…",
        loadError
: "Fehler beim Laden!"
   
},
});

10 Feedback, version history, credits and known issues

10.1 Credits

I am using the planize plugin by Nicolas Perriault for the table of contents.
I am using prettify.js by Mike Samuel for syntax highlighting in the of source code samples.

10.2 Feedback and support

First of all: this is work in progress.
Any kind of feedback is very welcome :-)

  • discussion forum is in place to ask questions or discuss features.
  • Check Stack Overflow for existing questions.
  • Use the Issue Tracker to get a list of known bugs, or vote for a feature.
    Please make sure you searched the group and issue tracker, before adding a new request.
  • If you like: Make a donation.


Posted by 1010
98..Etc/centos2014. 1. 3. 19:57
반응형

http://scotchblue.blogspot.kr/2012/08/centos-6x-nvidia-install-driver.html


centos 6.x nvidia install driver

1. www.nvidia.co.kr 에서 드라이버 다운

2.nouveau disable 시키기
etc/modprobe.d/disable-nouveau.conf 파일생성
내용 -> blacklist nouveau
            option nouveau modset=0

3.boot/grup/grup.conf 에디트 하기
내용 -> rdblacklist=nouveau 추가 하기
위치 -> kernel행 마지막에 넣어준다

NVIDIA~~.run 파일을 실행하기 위해서는 실행화일로 바꿔줘야 하기때문에
chmod a+x NVIDIA~~.run 이라고 실행한후에 ./NVIDIA~~.run 한다
64bit일 경우에는 설치도중 나오는 32bit는 깔지 않는다 깔아버리면 먹통되버린다.


Posted by 1010
98..Etc/centos2014. 1. 3. 13:57
반응형
http://efficient.tistory.com/entry/centos-ftp설치-및-설정
http://efficient.tistory.com/category/Linux
Posted by 1010
98..Etc/centos2014. 1. 3. 12:34
반응형

OS : CentOS 6.2

apache : 2.4.1

tomcat : 6.0 (6.9.35) (Binary)


1. tomcat 다운로드 & 압축해제

[root@CentOS ~]# cd /usr/local

[root@CentOS local]# wget http://mirror.apache-kr.org/tomcat/tomcat-6/v6.0.35/bin/apache-tomcat-6.0.35.tar.gz

[root@CentOS local]# tar xvfz apache-tomcat-6.0.35.tar.gz

[root@CentOS local]# ln -s apache-tomcat-6.0.35.tar.gz tomcat


http://www.apache.org/dist/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.35-src.tar.gz

Posted by 1010
98..Etc/centos2014. 1. 3. 12:32
반응형

1) Java SE Development Kit 6(JDK6) download

http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u31-download-1501634.html 

Linux x86(32-bit) jdk-6u31-linux-i586.bin 파일

 

2) 설치

mv /home/navi/Downloads/jdk-6u31-linux-i586.bin /usr/local  -> 파일 이동

cd /usr/local -> 디렉토리 변경

chmod 755 jdk-6u31-linux-i586.bin -> 파일 실행 권한 변경

./jdk-6u31-linux-i586.bin -> 설치

 

3) 환경변수 설정

ln -s jdk1.6.0_31 java -> java로 링크 설정

gedit /etc/profile -> 환경변수 설정 열기

export JAVA_HOME=/usr/local/java
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=$JAVA_HOME/jre/bin/lib/ext:$JAVA_HOME/lib/tools.jar

 

source /etc/profile -> 환경 변수 적용

 

env -> 설정한 환경변수 확인

 

java -version -> 최종적으로 java 설치 완료 확인(아래와 같이 나오면 정상 설치)

java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04)
Java HotSpot(TM) Server VM (build 20.6-b01, mixed mode)

 

4) openjdk 삭제 or java 순서 바꾸기

만약 자동적으로 openjdk가 설치되어 있다면, 새로 sun jdk설치 하였다고 하더라도

버전을 출력해보면...

#java -version

java version "1.6.0_22"
OpenJDK Runtime Environment (IcedTea6 1.10.6) (rhel-1.43.1.10.6.el6_2-i386)
OpenJDK Server VM (build 20.0-b11, mixed mode

위와 같이 openjdk가 기본적으로 딱 자리잡고 있다.

그러므로 이런경우 openjdk를 삭제하던 아니면 java config를 수정해서 기본 java path를

설치한 path로 잡아주어야 한다.


***삭제의 경우

rpm -qa | grep jdk

java-1.6.0-openjdk-devel-1.6.0.0-1.43.1.10.6.el6_2.i686
java-1.6.0-openjdk-1.6.0.0-1.43.1.10.6.el6_2.i686
java-1.6.0-openjdk-javadoc-1.6.0.0-1.41.1.10.4.el6.i686

yum remove java-1.6.0-openjdk-devel java-1.6.0-openjdk java-1.6.0-openjdk-javadoc


***그냥 두고 jdk 버전의 순서를 변경하는 경우

우선 현재 java config를 살펴보자

# update-alternatives --config java
3 개의 프로그램이 'java'를 제공합니다.
  선택    명령
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.6.0-openjdk/bin/java
   2           /usr/lib/jvm/jre-1.5.0-gcj/bin/java

자동적으로 설치된 openjdk가 자리잡고 있다.

그러므로, 위에 설치한 버전을 config에 추가하고 선택해주어야 한다.

우선 config에 추가

#update-alternatives --install "/usr/bin/java" "java" "/usr/local/jdk1.6.0_31/bin/java" <= 새로 설치한 path

그럼 추가가 됐는지 볼까요?

# update-alternatives --config java
3 개의 프로그램이 'java'를 제공합니다.
  선택    명령
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.6.0-openjdk/bin/java
   2           /usr/lib/jvm/jre-1.5.0-gcj/bin/java
   3           /usr/local/jdk1.6.0_31/bin/java


 현재 선택[+]을 유지하려면 엔터키를 누르고, 아니면 선택 번호를 입력하십시오 :

3)에 추가가됐네요! 그럼 3을 입력하고 엔터키...

# update-alternatives --config java

3 개의 프로그램이 'java'를 제공합니다.
  선택    명령
-----------------------------------------------
* 1           /usr/lib/jvm/jre-1.6.0-openjdk/bin/java
   2           /usr/lib/jvm/jre-1.5.0-gcj/bin/java
  +3           /usr/local/jdk1.6.0_31/bin/java


3이 선택된 것을 알 수 있습니다.

그리고 버전을 출력하면,

#java -version

Java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04)
Java HotSpot(TM) Server VM (build 20.6-b01, mixed mode)

위와 같이 위에서 설치한 sun Java가 잡혀있는 것을 볼 수 있다.

 

Posted by 1010
98..Etc/centos2014. 1. 3. 11:09
반응형

1. 디스크 파티션을 설정합니다. 웹서버를 사용할 목적이기에 파티션을 수동으로 잡습니다.

[사용자 레이아웃 만들기] 체크 하고 [다음] 클릭.


2. [만들기] 클릭 하고 [표준 파티션] 체크 하고 [생성]을 클릭합니다.

 

3. 순서는 상관없습니다. 저는 가상메모리로 사용될 "swap" 파티션 부터 잡아줬습니다.

[파일시스템 유형]에서 swap을 선택한후 용량은 자신의 RAM의 1.5 ~ 2배로 잡아줍니다.

저는 1024MB 이기 때문에 2048로 설정하고 [확인] 클릭.

 

4. swap 파티션이 설정되었습니다. [만들기] 클릭.

 

 

5. [/boot]는 부팅 시 부팅가능한 커널 이미지 파일의 공간입니다. 마운트 지점에 [/boot]를

선택하고 용량은 100MB로 설정합니다. 그리고 [첫번째 파티션으로 만듦] 을 체크합니다.

- 부팅 시 필요한 정보들의 공간임으로 많은 용량은 낭비입니다.

그리고 꼭 [첫번재 파티션 만듦] 체크하고 [확인] 클릭.

 

6. boot 파티션이 최상위로 설정 되었습니다. [만들기] 클릭.

 

7. root 파티션 설정입니다. 마운트 시점을 [ / ]선택 후 3072(3GB)로 설정후 [확인] 클릭.

 

8. root 파티션이 설정 되었습니다. [만들기] 클릭.

 

9. [/usr] 파티션 설정입니다. [마운트 지점] 에서 [/usr] 선택합니다.

시스템에 필요한 바이너리 파일, 라이브러리 파일, 커널 등 모여 있는 공간임으로 용량이

많이 필요하게 됩니다. 저는 8192(8GB)로 설정하였습니다.

 

10. usr 파티션이 설정 되었습니다. [만들기] 클릭.

 

11. [/var] 파티션 설정입니다. [마운트 지점]에서 [/var] 선택 합니다.

시스템 Log 들이 들어 있는 공간이고 웹서버의 기본적인 디렉토리 위치 및 메일서버에서

수신된 e-mail이 저장되는 공간입니다. 저는 4096(4GB)로 설정 하였습니다. [확인] 클릭.

 

12. var 파티션이 설정되었습니다. [만들기] 클릭.

 

13. [/tmp] 파티션 설정입니다. [마운트 지점]에서 [/tmp] 설정 합니다.

임시파일이 저장되는 공간입니다. /var 와 같은 크기로 설정합니다. [확인] 클릭.

 

14. [/data] 파티션 설정입니다. [마운트 지점] 에서 [/data] 선택 합니다. 백업하기 위한

파티션입니다. DB 서버로 사용할 경우에는 데이터가 누적되기 때문에 용량이 커야 됩니다.

저는 웹서버 이기때문에 2048(2GB) 설정 후 [확인] 클릭.

- 웹 서버 이용자 : [/data] 파티션 2GB 설정 후 [/home] 파티션에 남은 용량 모두 설정.

- DB서버 이용자 : [/home] 파티션 2GB 설정 후 [/data] 파티션에 남은 용량 모두 설정.

 

15. data 파티션이 설정되었습니다. [만들기] 클릭.

 

16. [/home] 파티션 설정입니다. [마운트 지점] 에서 [/home] 선택 합니다.

[가능한 최대 용량으로 채움]을 선택 한 후 [확인] 클릭.

 

17. 모든 파티션 설정이 끝이 났습니다. 확인 해보시고 확인 후엔 [다음] 클릭.

 

18. 설정한 파티션을 포맷할것인지 질문하는 창입니다. [포맷] 클릭.

 

19. 파티션을 디스크에 기록할 것인지 질문하는 창입니다. [디스크에 변경 사항 기록] 클릭.

 

20. 부트 로더 설정입니다. 부팅 시 CentOS에 로그인하기 전 비밀번호를 설정하는 것입니다.

비밀번호를 까먹으면 모든 데이터가 날아간다고 생각 하시면 되겠습니다.(찾질못하여)

개인적인 용도로 사용할 시에는 설정 할 필요가없습니다.

 

21. 웹서버용으로 시작하였지만 [Desktop]으로 체크한 아직까지 윈도우에 익숙하기 때문에

콘솔창에서 하다가 안되는 부분이 생기면 x 윈도우 모드에서 처리 하기 위해 [Desktop]

으로 선택. [server]와 관련하여 설치를 하게 되면 콘솔에서 밖에 사용이 안됩니다.

 

22. 설치전 설정은 끝났고 설치 중입니다.

 

23. 설치 완료~!


24. CentOS 6.3 Final 글자가 보이는 군요... Login을 하겠습니다.

 

25. 파티션이 잘 나눠졌는지 확인을 해보겠습니다.

[프로그램] -> [시스템도구] -> [디스크 도구] 클릭.

 

26. 설치 할때 설정 하였던 파티션이 제대로 설정 된 것을 확인 할수 있습니다.

Posted by 1010
98..Etc/centos2014. 1. 2. 23:13
반응형

1. http://www.centos.org/ 접속 > Downloads Mirrors > CentOS Public Mirror List

 

2. South American, Asian, Oceania, Middle Eastern, African and Other Regional Mirrors 선택

 

3. Korea 에서 선택 (http://ftp.neowiz.com/centos/)

 

4. 원하는 버전 선택 (6.4)

 

5. isos > i386(32bit) or x86_64(64bit) 선택

 

6. 설치방법에 따라 선택 (아래는 64bit 기준)

 

CentOS-6.4-x86_64-minimal.iso : 서버버전만 들은 미니멀버전

 

CentOS-6.4-x86_64-netinstall.iso : 저용량 버전으로 인터넷을 사용한 설치버전

 

CentOS-6.4-x86_64-bin-DVD1.iso : 일반적인 버전 (이것만 있어도 된다)

 

CentOS-6.4-x86_64-bin-DVD2.iso : 기초버전엔 필요없는듯..

 

CentOS-6.4-x86_64-bin-DVD1to2.torrent : 이왕이면 토렌트로 받자. 그냥 받으면 느리다.

 

설치할 버전을 CD/DVD/usb등에 담는다.

 

 

 

vmware/virtualbox 같은 가상머신을 사용할 거라면 다운받은 iso 파일만 잘 챙겨두면 된다.

 

 

 

 

출처 : http://webdir.tistory.com/113

Posted by 1010
98..Etc/centos2014. 1. 2. 23:02
반응형
Posted by 1010
98..Etc/centos2014. 1. 2. 22:51
반응형

CentOS 6.4 USB 설치하기


워낙 많이 널려있어서 이렇게 포스팅 하긴 뭐하지만 오늘 약 5대의 서버에 설치를 하면서 아무래도 문서로 남겨야 할 것 같아 이렇게 글을 적는다. 무엇보다 4G 메모리 스틱을 하나 날려먹었기 때문에 이를 기리기 위해서라도 꼭 남겨야 한다고 느꼈다.


1. ISO 이미지 다운로드 (CetnOS : http://centos.org/)

가장 먼저 할 일은 ISO 이미지를 다운 받는 것이다. CentOS 공식 홈페이지에서 다운로드가 가능 하며 Mirror 사이트에 한국 서버를 이용하면 빠른 속도로 다운이 가능하다.


ISO 이미지 파일이 여러가지가 있는데 Full Version은 Torrent로 DVD 1to2 를 다운받아야 하고 8G USB 메모리 스틱을 요구하기 때문에 간단하게 설치하고자 한다면 MInimal이 편하다. Full Version이 정말 필요한데 메모리스틱 용량이 적다면 Net Install 이미지를 다운 받아 설치하면 된다.


여기서는 Minimal 로 설치를 진행 할 예정이다. (아무리 생각해도 가장 편한 것 같다.)

 

-> http://ftp.daum.net/centos/6.4/isos/x86_64/

 

2. 가상 이미지 생성 iso2usb (iso2usb : http://iso2usb.sourceforge.net/)

USB를 먼저 PC와 연결시켜야 프로그램에서 인식 된다. 크게 다른 설정을 필요 없고 ISO 이미지만 선택해서 OK 버튼을 선택한다. 빠른 속도로 USB에 이미지가 들어간다.

 

3. USB 부팅

USB로 부팅 될 수 있도록 BIOS 설정을 수정해준다. 

여기까지는 기본 준비 사항이라고 볼 수 있다.

 

4. 설치 화면 

CentOS 설치 화면은 페도라와 큰 차이가 없다. 왜 그런지는 아시리라 믿는다.


[프롬프트 설치 화면]

언어 설정 : English 

키보드 타입 : us

설치 형태 : CD/DVD, HDD, URL, NFS(네트워크 드라이브)


[CD/DVD] 

- 해보지 않았지만 일반 CD/DVD 설치와 동일할 것으로 생각됨  


[Net install IMG 설치 진행]

- URL 선택, IPv6 체크 해제, 동적 IP, 고정 IP 체크

- MIRROR SITE : http://mirror.centos.org/centos/6.4/os/x86_64/

- 설치를 위해 필요한 기본적인 img를 다운 받는다. 다운이 완료 되면 GUI 설치 화면으로 넘어간다.


[Minamal 설치 진행]

- [dev/sda]를 선택, usb2iso 를 통해 이미지를 생성할 때 아무런 셋팅을 하지 않았다면 dev/sda 로 이미지가 생성된다.


[NFS]

- 설치를 진행해보지 않았지만 네트워크 드라이브 주소를 연결하는 부분이 있을 것으로 생각된다.


[GUI 설치 화면]


설치 저장공간 선택

[Basic storage devices] 선택


컴퓨터 이름 설정

localhost.localdomain 을 원하는 형태로 변경한다. 변경하지 않아도 무방하다.


최고관리자 비밀번호 설정

자신이 사용하고자 하는 비번을 설정한다. 약한 비번이라고 경고가 떠도 무시하면 그만. 

(테스트가 아니라면 꼭 강력한 비번 설정이 권장된다.)


시간 설정

[asia/seoul] 선택


네트워크 설정

시간 설정 화면 왼쪽 하단에 configure network 가 있다. 고정 IP가 아니면 설정 할 필요 없다.


파티션 설정

서버 용으로 설치했기 때문에 Use All Space를 선택해 lvm을 사용했다. 


직접 설정을 하고자 한다면 Create Custom Layout을 선택해 아래의 옵션에 맞춰 설정한다.

[swap] : HDD 일부를 RAM 처럼 사용하기 위해 잡는 공간으로 RAM의 2~3배 정도로 잡는다.

[ext4] : 파일 시스템의 일종이다. 

Mount 위치 :  /, /boot, /home 등이 있다. 직접 잡는 경우 /boot 에 500 Mb 를 할당해 부트로더를 설치한다.

자세한 파티션 설정을 다른 블로그를 참조 하도록 한다.


5. 부트로더 설치


[lvm] 그룹화할 HDD를 선택한 후 자신이 부트로더를 설치한 HDD를 선택하면 된다.

[Custom partition] /boot 마운트가 된 HDD에 설치된다.

부트로더는 자신이 원하는 위치로 바꿔서 사용해도 된다.

 

6. CentOS 설치 유형


[Desktop] 부팅시 x-windows 가 구동된다.

[Desktop minimal] 해보지 않았다! 

[Minimal] 운영체제가 돌아갈 수 있는 가장 기본적인 패키지만 설치 되있다.

[Basic Server] 해보지 않았지만 Server의 기본 패키지가 설치 되 있을 것 같다.

[Database Server] 어떤 DB가 설치되있는지는 모르겠다.

[Vhost Server] 잘 모르겠다.

[Web Server] Apache가 설치되있지 않을까?

[Softwear development workstation] 각종 라이브러리가 선물 보따리처럼 설치되어있을 것 같다.


결론은 그냥 Minimal에서 하나씩 올려 쓰는 걸 추천한다.

초기에 너무 많이 깔려있으면 무겁고 나중에 의존성 충돌나고 다시 설치할지도 모른다.

 

7. 설치 종료 후 네트워크 설정

설치가 끝나면 재부팅이 되고 덩그러니 로그인 커서만 깜빡인다.

로그인 root, 비밀번호는 아까 설정한 값을 입력하면 이제 본격적으로 디렉터리 접근이 가능하다.

아까 [시간 설정] 화면에서 Network 설정을 안했다면 일일히 다 입력을 해줘야 한다. 


# > ifconfig 


네트워크 장비가 뭐가 물려있나 본다. eth0 나 eth1 이 없다면 드라이버가 안잡혔거나 서비스로 올라오지 않은 거다.


# > ifconfig -a


전체 장비 목록을 확인 한다. eht 에 대한 정보가 나오면 드라이버는 정상적으로 잡혀 있다.

어떤 이더넷 카드가 물려있는 건지 확인 하려면 일단 이더넷 카드를 서비스에 올린다.


# > ifconfig eth0 up

서비스에 올리는 명령어는 up, 내리는 명령어는 down

up 한 상태에서 랜선을 뽑아 보면 ehternet down이라는 커맨드 라인이 뜬다. 이것으로 확인이 가능.


# > cd /etc/sysconfig/network-scripts/


위 경로에 접근 하면 각종 네트워크 장비들이 눈에 들어온다.


#> vi ifcfg-eth0


편집기로 이더넷 카드 정보를 읽는다.


onboot="no"


라고 되어있으면 "yes" 로 변경해준다.

편집기에서 저장 후 종료 한다.


# > service network restart


네트워크 서비스를 재시작하여 eth0가 정상적으로 올라오는지 확인한다.


# > ping 168.126.63.1

DNS까지 잘 가는지 확인해 본다.


#> yum update -y

잘 되면 yum으로 업데이트를 진행한다.


이것으로 기본적인 CentOS 설치 방법을 마무리 한다.

 

출처 : http://starkapin.tistory.com/496

Posted by 1010
98..Etc2013. 12. 26. 14:59
반응형

1. IE
https(보안통신)과 http(비보안 통신)을 혼용으로 사용 하였을 경우 IE에서는 경고 창이 발생 되고 혼용으로 볼 것인지 아니면
보안통신만 볼 것인지를 선택 할 수 있습니다.

123.jpg EXIF Viewer사진 크기536x163

 

보안통신만 사용 할 경우 ("예" 를 클릭하였을 경우) 암호화 통신을 하고 있다는 자물쇠 아이콘이 표시 됩니다.

3.jpg EXIF Viewer사진 크기393x66


비 보안통신과 보안통신을 혼용으로 사용 할 경우("아니오"를 클릭하였을 경우) 암호화 통신을 하고 있다는 자물쇠 아이콘이 표시 되지 않고 URL상 https만 유지 됩니다.

2. Firefox
https(보안통신)과 http(비보안 통신)을 혼용하여 사용 하였을 경우 혼용으로 사용중이라는 것을 안내하는 메시지가 출력됩니다.

12.jpg EXIF Viewer사진 크기539x127


확인을 클릭 할 경우 보안 통신을 하고 있다는 아래와 같은 내용이 출력 되지 않습니다.

5.gif


만약 보안통신만 사용하게 된다면 아래 그림과 같이 파란색 바가 출력됩니다.

2.jpg EXIF Viewer사진 크기585x280


3. Google
안내 메시지 및 경고 창이 발생되지 않고 비보안 통신과 보안 통신으로 혼용으로 사용하고 있다는 것을 표시합니다.

6.gif


보안통신만 사용할 경우 아래와 같이 보안통신만 사용하고 있음을 아이콘으로 표시합니다.

7.gif


위와 같이 혼용 관련 메시지를 뜨지 않게 할 경우 특정 경로 호출 값을 보안통신 또는 상대경로로 변경하시면 됩니다.

예를 들어,
CSS파일을 호출하거나,
js파일을 호출하거나,
플래시에 포하되어 있는 특정 경로에 있는 이미지 또는 파일을 호출하거나,
이미지 또는 파일을 호출하거나,
SSO를 위해 특정 경로로 정보값을 보내거나,
특정 경로의 파일을 include 하거나,

하는 경로를 보안통신(https) 또는 상대경로로 변경해 주시면 됩니다.

 

 

출처 : http://ucert.tistory.com/142

 

Posted by 1010
98..Etc2013. 12. 23. 20:43
반응형

HTTP 상태 코드

위키백과, 우리 모두의 백과사전.

아래는 HTTP(하이퍼텍스트 전송 프로토콜) 응답 상태 코드의 목록이다.

IANA가 현재 공식 HTTP 상태 코드 레지스트리를 관리하고 있다.

 

1xx (조건부 응답)[편집]

요청을 받았으며 작업을 계속한다.[1]

  • 100(계속): 요청자는 요청을 계속해야 한다. 서버는 이 코드를 제공하여 요청의 첫 번째 부분을 받았으며 나머지를 기다리고 있음을 나타낸다.
  • 101(프로토콜 전환): 요청자가 서버에 프로토콜 전환을 요청했으며 서버는 이를 승인하는 중이다.
  • 102(처리, RFC 2518)

2xx (성공)[편집]

이 클래스의 상태 코드는 클라이언트가 요청한 동작을 수신하여 이해했고 승낙했으며 성공적으로 처리했음을 가리킨다.

  • 200(성공): 서버가 요청을 제대로 처리했다는 뜻이다. 이는 주로 서버가 요청한 페이지를 제공했다는 의미로 쓰인다.
  • 201(작성됨): 성공적으로 요청되었으며 서버가 새 리소스를 작성했다.
  • 202(허용됨): 서버가 요청을 접수했지만 아직 처리하지 않았다.
  • 203(신뢰할 수 없는 정보): 서버가 요청을 성공적으로 처리했지만 다른 소스에서 수신된 정보를 제공하고 있다.
  • 204(콘텐츠 없음): 서버가 요청을 성공적으로 처리했지만 콘텐츠를 제공하지 않는다.
  • 205(콘텐츠 재설정): 서버가 요청을 성공적으로 처리했지만 콘텐츠를 표시하지 않는다. 204 응답과 달리 이 응답은 요청자가 문서 보기를 재설정할 것을 요구한다(예: 새 입력을 위한 양식 비우기).
  • 206(일부 콘텐츠): 서버가 GET 요청의 일부만 성공적으로 처리했다.
  • 207(다중 상태, RFC 4918)
  • 208(이미 보고됨, RFC 5842)
  • 226 IM Used (RFC 3229)

3xx (리다이렉션 완료)[편집]

클라이언트는 요청을 마치기 위해 추가 동작을 취해야 한다.[1]

  • 300(여러 선택항목): 서버가 요청에 따라 여러 조치를 선택할 수 있다. 서버가 사용자 에이전트에 따라 수행할 작업을 선택하거나, 요청자가 선택할 수 있는 작업 목록을 제공한다.
  • 301(영구 이동): 요청한 페이지를 새 위치로 영구적으로 이동했다. GET 또는 HEAD 요청에 대한 응답으로 이 응답을 표시하면 요청자가 자동으로 새 위치로 전달된다.
  • 302(임시 이동): 현재 서버가 다른 위치의 페이지로 요청에 응답하고 있지만 요청자는 향후 요청 시 원래 위치를 계속 사용해야 한다.
  • 303(기타 위치 보기): 요청자가 다른 위치에 별도의 GET 요청을 하여 응답을 검색할 경우 서버는 이 코드를 표시한다. HEAD 요청 이외의 모든 요청을 다른 위치로 자동으로 전달한다.
  • 304(수정되지 않음): 마지막 요청 이후 요청한 페이지는 수정되지 않았다. 서버가 이 응답을 표시하면 페이지의 콘텐츠를 표시하지 않는다. 요청자가 마지막으로 페이지를 요청한 후 페이지가 변경되지 않으면 이 응답(If-Modified-Since HTTP 헤더라고 함)을 표시하도록 서버를 구성해야 한다.
  • 305(프록시 사용): 요청자는 프록시를 사용하여 요청한 페이지만 액세스할 수 있다. 서버가 이 응답을 표시하면 요청자가 사용할 프록시를 가리키는 것이기도 하다.
  • 307(임시 리다이렉션): 현재 서버가 다른 위치의 페이지로 요청에 응답하고 있지만 요청자는 향후 요청 시 원래 위치를 계속 사용해야 한다.
  • 308(영구 리다이렉션, RFC에서 실험적으로 승인됨)

4xx (요청 오류)[편집]

4xx 클래스의 상태 코드는 클라이언트에 오류가 있음을 나타낸다.

  • 400(잘못된 요청): 서버가 요청의 구문을 인식하지 못했다.
  • 401(권한 없음): 이 요청은 인증이 필요한다. 서버는 로그인이 필요한 페이지에 대해 이 요청을 제공할 수 있다.
  • 403(금지됨): 서버가 요청을 거부하고 있다.
  • 404(찾을 수 없음): 서버가 요청한 페이지를 찾을 수 없다. 예를 들어 서버에 존재하지 않는 페이지에 대한 요청이 있을 경우 서버는 이 코드를 제공한다.
  • 405(허용되지 않는 방법): 요청에 지정된 방법을 사용할 수 없다.
  • 406(허용되지 않음): 요청한 페이지가 요청한 콘텐츠 특성으로 응답할 수 없다.
  • 407(프록시 인증 필요): 이 상태 코드는 401(권한 없음)과 비슷하지만 요청자가 프록시를 사용하여 인증해야 한다. 서버가 이 응답을 표시하면 요청자가 사용할 프록시를 가리키는 것이기도 한다.
  • 408(요청 시간초과): 서버의 요청 대기가 시간을 초과하였다.
  • 409(충돌): 서버가 요청을 수행하는 중에 충돌이 발생했다. 서버는 응답할 때 충돌에 대한 정보를 포함해야 한다. 서버는 PUT 요청과 충돌하는 PUT 요청에 대한 응답으로 이 코드를 요청 간 차이점 목록과 함께 표시해야 한다.
  • 410(사라짐): 서버는 요청한 리소스가 영구적으로 삭제되었을 때 이 응답을 표시한다. 404(찾을 수 없음) 코드와 비슷하며 이전에 있었지만 더 이상 존재하지 않는 리소스에 대해 404 대신 사용하기도 한다. 리소스가 영구적으로 이동된 경우 301을 사용하여 리소스의 새 위치를 지정해야 한다.
  • 411(길이 필요): 서버는 유효한 콘텐츠 길이 헤더 입력란 없이는 요청을 수락하지 않는다.
  • 412(사전조건 실패): 서버가 요청자가 요청 시 부과한 사전조건을 만족하지 않는다.
  • 413(요청 속성이 너무 큼): 요청이 너무 커서 서버가 처리할 수 없다.
  • 414(요청 URI가 너무 긺): 요청 URI(일반적으로 URL)가 너무 길어 서버가 처리할 수 없다.
  • 415(지원되지 않는 미디어 유형): 요청이 요청한 페이지에서 지원하지 않는 형식으로 되어 있다.
  • 416(처리할 수 없는 요청범위): 요청이 페이지에서 처리할 수 없는 범위에 해당되는 경우 서버는 이 상태 코드를 표시한다.
  • 417(예상 실패): 서버는 Expect 요청 헤더 입력란의 요구사항을 만족할 수 없다.
  • 418(I'm a teapot, RFC 2324)
  • 420(Enhance Your Calm, 트위터)
  • 422(처리할 수 없는 엔티티, WebDAV; RFC 4918)
  • 423(잠김,WebDAV; RFC 4918)
  • 424(실패된 의존성, WebDAV; RFC 4918)
  • 424(메쏘드 실패, WebDAV)
  • 425(정렬되지 않은 컬렉션, 인터넷 초안)
  • 426(업그레이드 필요, RFC 2817)
  • 428(전제조건 필요, RFC 6585)
  • 429(너무 많은 요청, RFC 6585)
  • 431(요청 헤더 필드가 너무 큼, RFC 6585)
  • 444(응답 없음, Nginx)
  • 449(다시 시도, 마이크로소프트)
  • 450(윈도 자녀 보호에 의해 차단됨, 마이크로소프트)
  • 451(법적인 이유로 이용 불가, 인터넷 초안)
  • 451(리다이렉션, 마이크로소프트)
  • 494(요청 헤더가 너무 큼, Nginx)
  • 495(Cert 오류, Nginx)
  • 496(Cert 없음, Nginx)
  • 497(HTTP to HTTPS, Nginx)
  • 499(클라이언트가 요청을 닫음, Nginx)

5xx (서버 오류)[편집]

서버가 유효한 요청을 명백하게 수행하지 못했음을 나타낸다.[1]

  • 500(내부 서버 오류): 서버에 오류가 발생하여 요청을 수행할 수 없다.
  • 501(구현되지 않음): 서버에 요청을 수행할 수 있는 기능이 없다. 예를 들어 서버가 요청 메소드를 인식하지 못할 때 이 코드를 표시한다.
  • 502(불량 게이트웨이): 서버가 게이트웨이나 프록시 역할을 하고 있거나 또는 업스트림 서버에서 잘못된 응답을 받았다.
  • 503(서비스를 사용할 수 없음): 서버가 오버로드되었거나 유지관리를 위해 다운되었기 때문에 현재 서버를 사용할 수 없다. 이는 대개 일시적인 상태이다.
  • 504(게이트웨이 시간초과): 서버가 게이트웨이나 프록시 역할을 하고 있거나 또는 업스트림 서버에서 제때 요청을 받지 못했다.
  • 505(HTTP 버전이 지원되지 않음): 서버가 요청에 사용된 HTTP 프로토콜 버전을 지원하지 않는다.
  • 506(Variant Also Negotiates, RFC 2295)
  • 507(용량 부족, WebDAV; RFC 4918)
  • 508(루프 감지됨, WebDAV; RFC 5842)
  • 509(대역폭 제한 초과, Apache bw/limited extension)
  • 510(확장되지 않음, RFC 2774)
  • 511(네트워크 인증 필요, RFC 6585)
  • 598(네트워크 읽기 시간초과 오류, 알 수 없음)
  • 599(네트워크 연결 시간초과 오류, 알 수 없음)

출처 : http://ko.wikipedia.org/wiki/HTTP_%EC%83%81%ED%83%9C_%EC%BD%94%EB%93%9C

Posted by 1010
98..Etc2013. 12. 23. 11:47
반응형

이 문서는 Gecko DOM 참고 자료의 목차입니다.

들면서

개요

DOM 요소 참고 자료

DOM window 참고자료

DOM document 참고자료

DOM event 참고자료

DOM style 참고자료

DOM range 참고자료

DOM selection 참고자료

DOM - 다른 객체

HTML Form 요소 인터페이스

HTML Table 요소 인터페이스

HTML Table Row 요소 인터페이스

DOM 예제

Posted by 1010
98..Etc2013. 11. 7. 10:56
반응형
Posted by 1010
98..Etc/Etc...2013. 2. 18. 10:28
반응형

출처 : http://www.ksug.org/94 

정상혁

이미 35개 이상의 Accenture 고객사에 Spring batch가 적용되고 있다

스프링배치 연재(1) 배치처리의 특징

스프링배치 연재(2) 대용량 처리 배치 프로그램을 만들 때 유의할 점

스프링배치 연재(3) 스프링배치 프로젝트와 주요 기능들

스프링배치 연재(4) 스프링배치의 구조와 구성요소들

스프링배치 연재(5) ItemReader와 ItemWriter

스프링배치 연재(6) 플랫파일 읽기와 쓰기

스프링배치 연재(7) XML파일 읽기와 쓰기

스프링배치 연재(8) JDBC를 이용한 Cursor 기반의 DB 조회

스프링배치 연재(9) JobRepository

스프링배치 연재(10) JobLauncher와 Job, Step

스프링배치 연재(11) 재시작과 재시도

스프링배치 연재(12) 이벤트 처리, 유효성 검사, 변환, 기존 클래스 활용

스프링배치 연재(13) 스프링배치의 형제들

스프링배치 연재(14) 드라이빙 쿼리와 iBatis의 활용

스프링배치 연재(15) 하이버네이트 활용과 여러파일 읽기

스프링배치 연재(16) DB to XML 파일 만들기 예제

배치 어플리케이션 실행 스크립트와 빌드

박찬욱님

엘레강스한 배치 추상화 프레임웍 - 스프링 배치

[Beta 1.0]Spring Batch 프레임웍 레퍼런스 한글 편역 버전.

[Beta 2.0] Spring Batch 프레임웍 레퍼런스 한글 편역 버전.

[Beta 3.0] Spring Batch 프레임웍 레퍼런스 한글 편역 버전.

제 1부. 스프링 배치 기본 아키텍처와 잡(Job) 직접 실행해보기

제 2부. FlatFileItemReader와 그 친구들(파트1)

제 2부. FlatFileItemReader와 그 친구들(파트2) (소스 및 PPT)

제 3부. FlatFileItemWriter와 아이템 변환하기 (소스 및 PPT)

제 4부. StAX 기반 아이템 처리 (소스 및 PPT)

제 5부. 데이터베이스에 아이템 쓰고, 읽고~ (소스 및 PPT)

제 6부. 배치 반복 처리하기

Spring Batch 쓰임새 분석 - 단순한 배치 반복하기

Spring Batch 쓰임새 분석 - 자동적인 재시작

Batch Processing Strategies at Spring Batch

스프링 배치's 액터(Actor)

Spring Batch 1.0에서 2.0으로 진화하기- 1. ItemReader/ItemWriter(1)

Spring Batch 1.0에서 2.0으로 진화하기- 1. ItemReader/ItemWriter(2)

Spring Batch 1.0에서 2.0으로 진화하기- 3. JobExecutionLisneter & 4. ItemProcessor

Spring Batch 1.0에서 2.0으로 진화하기- 5. Configuration

백기선님

The Domain Language of Batch - Spring Batch Chapter 2

ItemReader - Spring Batch Chapter 3

경구사님

Spring batch 개발환경 설정

김승권님

차세대배치시스템구축성공전략

- [Spring batch]차세대 배치시스템 구축 성공전략 - JCO컨퍼런스

박재성님

Spring Batch 시작하기

KSUG포럼

SpringBatch에 대한 경험담을 듣고 싶습니다.

Spring Batch ItemReader 구현체에 대한 궁금증

Posted by 1010
98..Etc/Etc...2013. 1. 11. 10:17
반응형

출처 : http://jaures.egloos.com/2290270 

 

Eclipse를 사용하다 보면 이런저런 이유로 속도가 느려지는 경험을 다 한 두번씩은 해봣을 것이다.
SVN repository에서 업데이트를 하는경우 build 작업하는 경우, 서버를 띄워서 작업을 하고 있는데 eclipse가 사용하는 메모리가 과도하게 늘어나서 문제가 생기는 경우 등등...

확실한 해결책은 아니겠지만, 나름대로 쾌적한(?) 환경에서 eclipse를 사용할 수 있도록 도와주는 방법을 몇가지 소개해본다.


1. Close Project

여러개의 project를 동시에 작업하는 경우에는 svn에서 update만 받아도 관련된 모든 project가 다시 빌드 작업을 진행해버려 그동안은 넋놓고 멍하니 기다리거나 작업의 리듬이 깨져버리는 경우가 많았다. 간혹 elcipse를 다시 재시작 해야하는 경우에도 재시작하는 시간이 너무 오래걸려 재시작을 고민해야 하는 경우도 종종 있었다.


이런 경우에는 해당 project를 닫아버리는게 큰도움이 되는데, 이건 아주 간단하게 바로 작업에 사용할 project가 아니라면 Package Explorer에서 해당 프로젝트의 컨텍스트 메뉴에서 "Close Project"를 해버리면 된다. 작업할 때에는 다시 컨텍스트 메뉴에서 "Open Proejct"를 하면 된다.


2. Spelling 검사 끄기

필요한 경우도 있겠지만, 대다수의 경우에는 철자검사를 할필요는 없을것 같다. 철자검사를 해제하면 에디터상에서 철자에 대한 검사를 실행하지 않기 때문에 조금은 더 빠르게 작업을 할수 있다.


Window > Preferences > General > Editors > Text Editors > Spelling 에서 Enable spell checking 체크박스를 해제하면 된다.


3. Startup and Shutdown

Eclipse plug-in을 이것저것 설치해서 사용하다보면 시작시에 불필요한 작업이 많아진다. 꼭 그런것은 아니지만 시작시에 plug-in의 업데이트를 확인한다거나 plug-in의 특정 모듈을 activate 한더거나 등등.

작업에 꼭 필요하지 않다고 생각되는 것들은 시작 항목에서 빼버리게 되면 그만큼 eclipse의 시작 실행속도가 빨라지게 된다. 이 항목에서는 또한 eclipse 종료시에 대한 설정도 할수 있다.


Window > Preferences > General > Startup and Shutdown > Plug-ins activated on startup 에서 사용하지 않을 항목에 대해 체크박스를 해제하면 된다.


4. Eclipse status memory monitor

Eclipse는 JRE 위에서 실행되는 java 프로그램이라서 eclipse를 실행한 후에 일정 기간이 지나게 되면 Gabarge Collection을 하게 된다. 더군다나 eclipse는 많은 메모리를 사용하는 것으로 악명(?)이 높기 때문에 GC가 제때 수행되지 않거나 주기가 길어지는 경우 프로그램을 실행할 메모리 자체가 줄어들어 작업 자체가 힘들어진다.

이럴 경우 Eclipse status memory monitor plug-in을 사용해 메모리가 모자르다 싶으면 바로 GC를 강제로 수행해 메모리를 확보할 수 있다. 또한 현재 Eclipse가 사용하고 있는 메모리의 상태를 직접 확인할 수 있으므로 아무런 이유없이 eclipse가 느려지는 답답함을 해소(?)할 수도 있다.




5. Validation

보통 view 작업을 진행하다 보면, 여러가지 코드가 한 파일에 뒤섞이게 된다. JSP 파일안에 html, css, javascript, java 등의 코드들이 뒤섞에 있다보면 validation이 크게 의미가 없게 되는 경우가 있는데 이럴 경우에는 굳이 validation을 할필요가 없어지게 된다. Validation은 에디터상에서 말그대로 문법에 대한 오류를 실시간으로 검사해 알려주는 것이기 때문에 validation만 해제해도 eclipse 작업속도에 그 만큼의 영향을 미치게 된다.


Window > Preferences > General > Validation > Validator 항목에서 문법검사를 하지 않을 항목에 대해 체크를 해제하면 된다.
Posted by 1010
98..Etc/Etc...2012. 10. 17. 07:18
반응형

카테고리 : Domain-Driven Design

2010/03/31 Domain-Driven Design Essence [21]
2009/10/15 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 11부 [完] [15]
2009/10/13 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 10부
2009/07/29 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 9부
2009/07/13 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 8부 [2]
2009/06/29 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 7부
2009/06/23 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 6부 [2]
2009/06/15 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 5부
2009/03/25 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 4부 [4]
2009/02/27 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 3부
2009/02/23 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 2부
2009/02/15 Domain-Driven Design의 적용-4.ORM과 투명한 영속성 1부
2009/01/18 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 7부 [2]
2009/01/02 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 6부
2008/12/24 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 5부 [2]
2008/12/17 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 4부
2008/12/13 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 3부
2008/12/09 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 2부
2008/12/05 Domain-Driven Design의 적용-3.Dependency Injection과 Aspect-Oriented Programming 1부
2008/11/30 Domain-Driven Design의 적용-2.AGGREGATE와 REPOSITORY 5부
2008/11/27 Domain-Driven Design의 적용-2.AGGREGATE와 REPOSITORY 4부
2008/11/25 Domain-Driven Design의 적용-2.AGGREGATE와 REPOSITORY 3부 [2]
2008/11/23 Domain-Driven Design의 적용-2.AGGREGATE와 REPOSITORY 2부
2008/11/20 Domain-Driven Design의 적용-2.AGGREGATE와 REPOSITORY 1부
2008/11/17 Domain-Driven Design의 적용-1.VALUE OBJECT와 REFERENCE OBJECT 4부 [4]
2008/11/17 Domain-Driven Design의 적용-1.VALUE OBJECT와 REFERENCE OBJECT 3부
2008/11/16 Domain-Driven Design의 적용-1.VALUE OBJECT와 REFERENCE OBJECT 2부 [4]
2008/11/15 Domain-Driven Design의 적용-1.VALUE OBJECT와 REFERENCE OBJECT 1부 [14]

 

Posted by 1010
98..Etc/jQuery2012. 10. 3. 05:10
반응형

Getting Started with jQuery Mobile

jQuery Mobile provides a set of touch-friendly UI widgets and an AJAX-powered navigation system to support animated page transitions. Building your first jQuery Mobile page is easy, here's how:

Create a basic page template

Pop open your favorite text editor, paste in the page template below, save and open in a browser. You are now a mobile developer!

Here's what's in the template. In the head, a meta viewport tag sets the screen width to the pixel width of the device and references to jQuery, jQuery Mobile and the mobile theme stylesheet from the CDN add all the styles and scripts. jQuery Mobile 1.1 works with both 1.6.4 and 1.7.1 versions of jQuery core.

In the body, a div with a data-role of page is the wrapper used to delineate a page, and the header bar (data-role="header") and content region (data-role="content") are added inside to create a basic page (these are both optional). These data- attributes are HTML5 attributes are used throughout jQuery Mobile to transform basic markup into an enhanced and styled widget.


<!DOCTYPE html> 
<html> 
	<head> 
	<title>My Page</title> 
	<meta name="viewport" content="width=device-width, initial-scale=1"> 
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
	<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head> 
<body> 

<div data-role="page">

	<div data-role="header">
		<h1>My Title</h1>
	</div><!-- /header -->

	<div data-role="content">	
		<p>Hello world</p>		
	</div><!-- /content -->

</div><!-- /page -->

</body>
</html>

Add your content

Inside your content container, you can add any standard HTML elements - headings, lists, paragraphs, etc. You can write your own custom styles to create custom layouts by adding an additional stylesheet to the head after the jQuery Mobile stylesheet.

Make a listview

jQuery Mobile includes a diverse set of common listviews that are coded as lists with a data-role="listview" added. Here is a simple linked list that has a role of listview. We're going to make this look like an inset module by adding a data-inset="true" and add a dynamic search filter with the data-filter="true" attributes.


<ul data-role="listview" data-inset="true" data-filter="true">
	<li><a href="#">Acura</a></li>
	<li><a href="#">Audi</a></li>
	<li><a href="#">BMW</a></li>
	<li><a href="#">Cadillac</a></li>
	<li><a href="#">Ferrari</a></li>
</ul>

 

Add a slider

The framework contains a full set of form elements that automatically are enhanced into touch-friendly styled widgets. Here's a slider made with the new HTML5 input type of range, no data-role needed. Be sure to wrap these in a form element and always properly associate a label to every form element.


<form>
   <label for="slider-0">Input slider:</label>
   <input type="range" name="slider" id="slider-0" value="25" min="0" max="100"  />
</form>

 

Make a button

There are a few ways to make buttons, but lets turn a link into a button so it's easy to click. Just start with a link and add a data-role="button" attribute to it. You can add an icon with the data-icon attribute and optionally set its position with the data-iconpos attribute.


<a href="#" data-role="button" data-icon="star">Star button</a>

Star button

Play with theme swatches

jQuery Mobile has a robust theme framework that supports up to 26 sets of toolbar, content and button colors, called a "swatch". Just add a data-theme="e" attribute to any of the widgets on this page: page, header, list, input for the slider, or button to turn it yellow. Try different swatch letters in default theme from a-e to mix and match swatches.

Cool party trick: add the theme swatch to the page and see how all the widgets inside the content will automatically inherit the theme (headers don't inherit, they default to swatch A).

<a href="#" data-role="button" data-icon="star" data-theme="a">Button</a>data-theme="a" data-theme="b" data-theme="c" data-theme="d" data-theme="e"

When you're ready to build a custom theme, use ThemeRoller to drag and drop, then download a custom theme.

Go forth and build stuff

This is just scratching the surface of all the cool things you can build with jQuery Mobile with little effort. Be sure to explore linking pages, adding animated page transitions, and creating dialogs. Use the data-attribute reference to try out some of the other data- attributes you can play with.

More of a developer? Great, forget everything we just covered (kidding). If you don't want to use the data- attribute configuration system, you can take full control of everything and call plugins directly because these are all just standard jQuery plugins built with the UI widget factory. Be sure to dig into global configuration, events, and methods. Then read up on scripting pages, generating dynamic pages, and building PhoneGap apps.

Posted by 1010
98..Etc/Sencha Touch2012. 10. 3. 00:55
반응형
Posted by 1010
98..Etc/Sencha Touch2012. 7. 17. 14:06
반응형

출처 : http://blog.naver.com/PostView.nhn?blogId=herossg&logNo=100160797127



(최종 결과 물)



*** 이 페이지는 제가 초보적인 수준에서 작성된 게시물이며,

그냥 지워 버릴까 생각하다가 이 게시물을 보면서

다시 한번 맘 가짐을 고치기 위해 보관 중입니다.

Sencha touch 를 공부 하시는 분들 이 게시물은

초보적인 도움뿐이 안됩니다.

다른 게시물을 이용하기 바랍니다.



하이브리드 앱을 만들기 위해서 이것 저것 기웃 거리다 Sencha Touch 2.0.1 을 이용해 보기로 했다.


1. 로그인창 만들기

로그인창은 즐겨찾기 등에 대한 정보를 개인 모바일 기기가 아닌 서버에 저장하고

다른 모바일 기기에서도 굳이 새로 등록 하는게 아니라 ID / PW 를 이용하여 동일하게

적용하기 위함.


목표 : 1. E-mail / Password 입력 받기

2. Button 클릭으로 localStorage에 저장해서 다음에 재 사용하기...


우선 기본적인 개발 환경이 준비 되었다고 가정하고 시작함.


Sencha 는 나름 MVC 모델을 이용하여 프로그램을 할 수 있음.

MVC 모델에 자세한 사항은 네이버 검색을 이용하면 됨.


위 목표를 완료 하기 위해서는 우선

HTML 페이지를 하나 만들어 야 한다.


파일명 : index.html

<html>

<head>

<meta charset="utf-8">


<!-- Sencha Touch CSS -->

<link rel="stylesheet" href="./css/sencha-touch.css" type="text/css"> <!-- Sencha Touch 에 사용되는 CSS 파일 -->


<!-- Sencha Touch JS -->

<script type="text/javascript" src="./js/sencha-touch-all-debug.js"></script><!-- Sencha Touch 에 Import -->


<!-- Application JS -->

<script type="text/javascript" src="./js/app.js"></script> <!-- Sencha Touch 의 Application -->

<script type="text/javascript" src="http://apis.daum.net/maps/maps3.js?apikey=다음지도API 키"></script>

<!-- 다음 지도 api 를 import 하기 위한 구문이며 apikey 는 다음 개발자 사이트에서 신청해서 사용함 -->

</head>

<body></body>

</html>


위 소스가 HTML 소스의 전부 이다.


그리고 application Script 파일을 작성해야 함.


파일명 : app.js


Ext.application({

name: 'Nubija', <!-- 봐서 알겠지만 최종목표는 다음지도를 이용한 누비자 터미널 정보를 보는것이다. -->

appFolder: './js/app',

<!-- Html 파일이 있는 홈의 하위 폴더 인 "./js/app" 하위에 view / controller / model 폴더가 존재 해야 함. -->

views: ['LoginView'],

<!-- Sencha Touch 의 View 파일 설정함 -->

controllers: ['LoginController'],

<!-- Sencha Touch 의 Controller 파일 설정함 -->


launch: function() { <!-- launch 는 페이지가 모두 로딩되고 application 이 실행되면서 { .. } 안에 문장 수행 -->

Ext.create('LoginView'); <!-- Ext.create 명령을 이용하여 View 생성 -->

}

});


이제 View Script 를 작성한다.

파일명 : LoginView.js


Ext.define('Nubija.view.LoginView', {
extend: 'Ext.Panel',
alias: 'LoginView',
config : {
fullscreen : true,
layout : 'vbox',
items : [
{ <!-- fieldset 시작 -->
<!-- fieldset을 사용하면 하위 componet ( ex : emailfield / passwordfield ) 에 id 를 부여 할 수 없었다.
할수 있는 방법이 있는데 내가 모르는 것일 수도 있지만, 하여간 몇일 고민했는데 찾을 수 없었다.
id 를 부여 할 수 없으면 Controller 에서 값을 읽을 방법을 몰라 한참을 해메다가 ...
그냥 꼼수를 부려서 처리 했다.

그 꼼수는 controller 에서 확인 하면 됨.

-->
xtype : 'fieldset',
title : '개인 식별을 정보 입력',
items : [
{
xtype : 'emailfield', <!-- Email 형식의 Text 박스 정의 -->
label : '이메일',
name : 'email',
placeHolder:'이메일을 입력하세요.',
required:true
},
{
xtype : 'passwordfield', <!-- Password 형식의 Text 박스 정의 -->
label : '암호',
name : 'password',
placeHolder:'암호를 입력하세요.',
required:true
},
{
xtype : 'label',
html : '<FONT SIZE = 1>* 이 정보는 개인 구분을 위해서만 사용됩니다.</font>'
}
]
},<!-- fieldset 끝 -->
{<!-- toolbar 시작 -->
xtype: 'toolbar',
docked: 'bottom',
ui: 'light',
defaults: {
iconMask: true
},
items: [
{ xtype: 'spacer' }, <!-- toolbar에 왼쪽 공간 공백 -->
{ iconCls: 'action', <!-- 버튼 추가 -->
title: '완료',
id:'LoginButton'},<!-- 버튼 id 는 controller 에서 Event 처리 등에 사용한다. -->
{ xtype: 'spacer' }<!-- toolbar에 오른쪽 공간 공백 -->
]
}<!-- toolbar 끝 -->
]
}
});

이제 마지막으로 가장 중요한 Controller 이다.

파일명 : LoginController.js


Ext.define('Nubija.controller.LoginController', {
extend: 'Ext.app.Controller',
alias: 'LoginController',
config :{
refs : {
LoginButton:'#LoginButton' <!-- view 에서 정의한 버튼 id 를 참조하고 -->
},
control : {
LoginButton :{
tap : 'onLoginButton' <!-- 버튼이 눌러졌을때 수행할 function 를 정의 한다. -->
}
}
},
onLoginButton:function() {
var email = Ext.get("ext-element-12").getValue(); <!-- 이부분이 정말 꼼수다. -->
<!-- Sencha Touch 에서 Ext.get("id").getValue() 이렇게 해서 해당 id 의 값을 가져 올수 있다.
그런데 filedset 의 하위 component 는 id 를 부여 할 수 없었다.
그래서....
그 방법은 밑에서 자세히 ID 아아 내는 방법을 표시 함.
-->
var pw = Ext.get("ext-element-18").getValue();
console.log("LoginButton Click !! - " + email + ", " + pw );
localStorage.setItem('email', email ); <!-- HTML5 에서 추가된 localStorage 명령을 이용하여 Local 에 저장함-->
localStorage.setItem('password', pw );
},
init:function() {
this.callParent();
console.log("init LoginController : " + localStorage.getItem('email'));
}
});

끝. 일단 여기 까지 하면 대강 로그인 창을 만들수 있다.


담에는 다음 지도를 화면에 표시 하는 방법에 대해서 해야 겠다.


PS : 위에서 언급한 꼼수...


위 프로그램을 실행 하고 크롬의 개발자 도구를 이용하여 Element 기능을 이용하여 ID 를 찾았다.

소스가 바뀌지 않는 이용 Sencha touch 에서 자동 생성하는 id 값은 변경 되지 않는다. 아마도...




Posted by 1010
98..Etc/Sencha Touch2012. 7. 17. 11:21
98..Etc/Sencha Touch2012. 7. 16. 17:48
반응형

출처 : http://coronasdk.tistory.com/163

 

지난번까지 Sencha Touch 에 대해 대략적으로 알아보고 SDK를 설치하고 그리고 어플리케이션을 하나 만들어 봤습니다.

어플리케이션을 만들어보니 대충 감이 잡히던데요.

일단 Sencha Touch에서 제공하는 Tutorial을 한번 훑어보는게 센차터치를 좀 더 디테일하게 알 수 있는 가장 좋은 방법인것 같습니다.

Corona SDK도 코로나에서 제공하는 튜토리얼인 Corona DOC를 한번 다 훑고 나서 새로 추가되는 기능들을 하나하나 정리해 나가니까 정말 도움이 되더라구요.

오늘부터는 우공이산이라고 하나하나 기초적인 튜토리얼부터 공부해 나가볼 생각입니다.

***** Sencha Touch란?
센차터치란 안드로이드나 iOS, 블랙베리 같은 모바일 폰에 HTML5를 기반으로 앱을 쉽고 빠르게 만들 수 있도록 해 줍니다.

***** 필요한 것은?
- Sencha Touch 2.0 SDK beta
- 웹 서버 (로컬)
- 웹 브라우저 최신버전 (크롬하고 사파리를 추천합니다.)
=> 보다 자세한 사항은 제 글 Sencha Touch getting started - 설치 및 예제 실행 - 를 참조하세요.

***** 시작하기
웹 서버를 설치하지 않아도 아래 두개 파일만 있어도 예제를 실행할 수는 있습니다.
sencha-touch.css

sench-touch-all-debug.js

위 두 파일을 임의의 폴더에 복사해 넣으세요.
그리고 아래 html 파일을 작성해 넣으세요.

<!DOCTYPE html>
<html>
<head>
    <title>Getting Started</title>
    <link rel="stylesheet" href="sencha-touch.css" type="text/css">
    <script type="text/javascript" src="sencha-touch-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body></body>
</html>

html파일 이름은 마음대로 정하셔도 됩니다.
이제 app.js파일을 만드셔서 코딩을 하시면 됩니다.

첫번째 코딩은 alert화면 띄우기 입니다.
Ext.application({
name: 'Sencha',

launch: function() {
alert('launched');
}
});

이렇게 작성하시고 html파일을 브라우저에서 실행해 보세요.


이렇게 alert화면이 뜨면 성공하신겁니다.

app.js를 아래와 같이 바꾸고 실행해 보세요.
Ext.application({
name: 'Sencha',

launch: function() {
Ext.create('Ext.Panel', {
fullscreen: true,
html: 'Hello World'
});
}
});

그러면 이렇게 Hello World가 나올 겁니다.
Ext.create()는 Ext.ClassManager.instantiate를 간단히 사용하기 위해 만든 겁니다.
Ext.create()대신 Ext.ClassManager.instantiate를 넣으셔도 결과는 똑 같습니다.
instantiate(String name, Mixed args) 가 신택스 입니다.

Tutorial 첫 시간은 여기까지 하겠습니다.
앞으로 Sencha Touch에서 공식적으로 제공하는 Tutorial을 기반으로 글을 정리해 나가겠습니다.

다음 시간에 뵈요....

Posted by 1010
98..Etc/Sencha Touch2012. 7. 16. 17:42
반응형

출처 : http://blog.saltfactory.net/139



Sencha Touch는 아이폰, 안드로이드, 블랙베리 등 다양한 모바일 디바이스의 웹 앱 개발을 지원하는 자바스크립트 프레임워크이다. 자바스크립트 프레임워크라는 말에 촛점을 맞출 필요가 있는 이유는 Sencha Touch는 거의 대부분의 코드를 Javascript로 생성하기 때문이다. Appspresso(앱스프레소)를 이용해서 하이브리드 앱을 개발하는 방법에 대해서 포스팅하는 가운데 UI javascript 프레임워크 선정할때 후보로 Sencha Touch와 JQuery Mobile, JTouch 를 생각했는데 가장 네이티브 앱에 가까운 다양한 UI 제공과 MVC 프로그래밍을 할 수 있게 설계되어 있는 아키텍처 때문에 Sencha를 HTML5 를 이용한 하이브리드 앱 개발의 UI 프레임워크로 결정했다. (HTML5 기반 앱을 만들기위해서 미리 구입한 Sencha Touch 책이 있기 때문이기도 했는데 현재 판매되고 있는 것은 Sencha Touch 1.x 기반의 책들이다. Sencha Touch 2와 Sencha Touch 1은 구조 자체가 달라졌기 때문에 이전 책을 구입하면 조금 당항할 수도 있다. 물론 Sencha 공식 사이트에서 migration 정보를 문서로 제공하고 있지만 처음부터 Sencha Touch 2로 시작하는 것을 추천하고 싶다.) 하이브리드 앱 개발하는 과정에서 UI 프로그래밍은 필수 조건이다. 그래서 Appspresso에 관련된 포스팅에 연결해서 연재하려고 하다가 Sencha 자체만해도 내용이 방대하고 어렵기 때문에 Sencha라는 카테고리로 분리해서 작성하려고 한다. (참고로 jQuery 정로도 생각하면 정말 이해하는데 어려움을 겪을수 있다.)


[자세히 보기]



[관련 내용]

<참고>

http://docs.sencha.com/touch/2-0/#!/guide/command


<Appsrpesso 튜토리얼 관련 포스트>

http://blog.saltfactory.net/category/Appspresso


<Sencha Touch 2 튜토리얼 관련 포스트>

1. Sencha Touch 2 (센차터치)를 이용한 웹앱 개발 - 1. 설치, 생성, 패키징, 빌드(device, simulator)

2. Sencha Touch 2 (센차터치)를 이용한 웹앱 개발 - 2. 뷰(View) 생성

3. Sencha Touch 2 (센차터치)를 이용한 웹앱 개발 - 3. 뷰(View) 구성 - 컴포넌트 생성,구성

4. Sencha Touch 2 (센차터치)를 이용한 웹앱 개발 - 4. 뷰(View) 구성 - Navigation Components

5. Sencha Touch 2 (센차터치)를 이용한 웹앱 개발 - 5. 뷰(View) 구성 - Store-bound components (리스트 뷰)

6. Sencha Touch 2 (센차터치)를 이용한 웹앱 개발 - 6. 뷰(View) 구성 - Form components (폼 구성)


[샘플 자료]

http://dev.sencha.com/deploy/touch/examples/production/index.html


[번역 가이드]

http://greatgrape.co.kr/wp-content/uploads/2012/01/발로번역한_센차터치2_가이드.pdf

[라이센스 관련]

http://www.sencha.com/products/touch/license/


[Demo]

http://senchatouch.happydong.kr

Posted by 1010
98..Etc/Sencha Touch2012. 7. 16. 17:38
반응형

센차터치는 기본 웹 리소스(자바스크립트, CSS, HTML 등)만으로 구성된 프레임워크이므로 별도의 프로그램 설치과정이 필요없습니다.
단지 라이브러리 파일만 내려받기 하면 됩니다.
아래의 주소에서 다운로드 받을 수 있습니다.

다운로드 : http://www.sencha.com/products/touch/download

다운로드 홈페이지에 접속해보면 하나는 오픈 소스 버젼으로 현재 1.1.1버젼이고 또 하나는 개발자 버젼으로 2.0.0 버젼입니다.

Sencha Touch 구성 1

센차터치 구성 및 폴더의 구조

압축파일의 압축을 풀면 여러가지 폴더와 파일이 나옵니다. 핵심 라이브러리와 도움말, 예제 애플리케이션, 기타 리소스가 모두 포함되어 있습니다.

Sencha Touch 구성 2


몇가지 파일과 폴더의 내용을 살펴보겠습니다.

센차터치 핵심 라이브러리.

센차터치 애플리케이션 개발을 위해서는 반드시 포함해야 할 파일입니다.

sencha-touch.js

Sencha Touch 코어가 구현된 자바스크립트 파일입니다.
바로 루트(root)폴더에 있으며 압축된 버젼입니다. 개발시에는 sencha-touch-debug.js 를 참조하는것이 좋습니다.
이는 압축되지 안아서 참고할 수 있습니다.

sencha-tou.css

센차터치 애플리케이션 외형을 정의하는 css 파일입니다.
이 파일 역시 핵심 라이브러리로 모든 애플리케이션에서 반드시 포함해야 하는 파일입니다.
이 파일은 resources/css 폴더에 있습니다.

doc 폴더.

Sencha Touch API Documentation , 즉 API 설명서를 그대로 옮겨놓은 것입니다. 다음의 사이트에서도 동일한 내용을 볼 수 있습니다.
http://docs.sencha.com/touch/1-1/
센차터치는 다른 프레임워크에 비해 API 가 방대하고 복잡해서 설명서를 참조할 일이 많습니다.
API 문서에서는 센차터치의 각종 컴포넌트와 관련한 상세한 설명을 볼 수 있으며, 클래스의 계층구조와 메서드(함수), 매개변수 등의 정보를 얻을 수 있습니다.

examples 폴더.

센차터치로 개발한 실제 동작하는 예제 애플리케이션을 모아 놓은 폴더입니다.
UI 구성, Ajax 상호작용, 애니메이션, 터치 이벤트, 멀티미디어 구현 등 센차터치가 제공하는 기능을 이용한 실제 구현 사례가 포함되어 있으며, 루트에 있는 index.html 를 실행하면 전체 예제에 대한 바로가기를 확인 할 수 있습니다.
온라인에서도 제공되는데 아래의 URL에서 확인할 수 있습니다.
http://dev.sencha.com/deploy/touch/examples/

Sencha Touch 구성3


examples 폴더는 아래처럼 에제별로 분리되어 있습니다.
각 폴더마다 하나의 기능을 수행하는 에제 파일이 들어 있습니다.

Sencha Touch 구성4


 

resource 폴더.

이 폴더에는 앞서 설명한 sencha-touch.css 파일을 비롯해 테마 관련 파일과 이미지 파일, Sass 기반의 스타일 정의 파일이 존재합니다.

Posted by 1010