태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

롸이언의 인생이야기 @ Innovate yourself ™

'ajax'에 해당되는 글 2건

  1. 2008/08/25 AJAX의 XMLHttpRequest 객체에 대해
  2. 2008/06/18 Lightbox JS

XMLHttpRequest(XHR) 객체는 Internet Explore5에서 ActiveX 컴포넌트 형식으로 가장 먼저 제공되었기때문에, 모질라와 사파리 웹브라우저에서 이 객체를 도입하기전까지 사실 많은 개발자들이 XMLHttpRequest 객체의 사용을 꺼려했다.

XHR은 W3C 표준이 아니기때문에 브라우저마다 작동방식에 있어서 다소나마 차이가 존재했었지만 현재 대부분의 브라우저들은 XHR 기능을 서로 비슷하게 구현하고 있다.
현존하는 브라우저들 중에서 XHR을 지원하지 않는 브라우저는 거의 없을정도로 대부분의 브라우저들은 현재 XHR 을 지원하고 있다.

ajax 구현의 시작은 XHR 객체의 생성에서 시작한다.
XHR 은 W3C 의 표준이 아니므로, 인터넷익스플로어에서는 ActiveX Component 형식으로 구현되었고, 그 밖에 다른 브라우저들(FireFox, Safari, Opera)은 native javascript 객체로 구현되었다.
이런 차이점을 고려해서 XHR 객체를 얻어오는 자바스크립트 코드를 다음과 같이 작성할 수 있다.

var xmlHttp;

function createXMLHttpRequest() {
     if(window.ActiveXObject) {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     } else if(window.XMLHttpRequest) {
          xmlHttp = new XMLHttpRequest();
     }
     return xmlHttp;
}

window.ActiveXObject 는 ActiveXObject를 지원하는 브라우저라면 오브젝트를 리턴하고 그렇지 않다면 null를 리턴하게 된다.
따라서 오브젝트가 존재하면 if 구문은 true 를 반환하고 xmlHttp 값은 ActiveXObject 객체가 할당되어진다. if 구문이 false 를 반환하면 else 구분으로 이동하여 xmlHttp 값은 navtive javascript 객체가 할당될 것이다.
따라서 위 코드를 이용하면 브라우저가 다르더라도 하나의 메소드로 XHR 객체를 생성할 수 있다.


XHR 오브젝트의 메소드

void open(method, url, [async, [user, [ password ]]])
     요청을 초기화한다.

     method : GET/POST
     url : 요청대상 URL
     async : 비동기 true, 동기 false (default : true)
     user : 인증페이지에서 사용될 사용자 이름
     password : 인증페이지에서 사용될 암호

async 을 false 로 설정하면 요청은 동기로 처리되기 때문에 서버에서 응답을 받을때까지 프로세스는 기다린다.
XHR 을 사용하는 가장 큰 이점중의 하나인 비동기 처리를 위해서는 asynch 항목을 true 로 설정해야 한다.
false 를 설정한다면 XHR 을 사용하는 이점이 그만큼 줄어든다.


void send(content)
실질적으로 요청을 서버로 보낸다.
요청이 비동기이면 이 메소드는 바로 리턴되지만 요청이 동기이면 서버에서 응답을 받을때까지 계속 대기한다.
content 는 선택사항이며, DOM 객체이거나 input stream, string 값으로 설정할 수 있으며 HttpRequest body 의 한 부분으로 서버로 전달된다.
(※content 에 값을 넘기려면 open() 메소드는 반드시 POST 로 설정해야 하며, GET 방식으로 요청하려면 null 을 설정하면 된다.)

open(), send() 메소드가 가장 많이 사용되는 메소드들이다.
나머지 메소드에 대해서도 알아보자.

void setRequestHeader(string header, string value)
     header 에 해당하는 value 값으로 HttpRequest  헤더에 값을 설정하는 메소드이다.
     반드시 open() 메소드 다음에 위치해야 한다.

void abort()
     요청을 중지한다.

string getAllResponseHeaders()
     요청에 대응되는 응답의 헤더정보를 리턴한다.
     즉, Content-Length, Date, URI 등을 포함하는 헤더정보를 string 형식으로 반환한다.

string getResponseHeader(string header)
     응답의 헤더정보중에서 header 에 대응되는 값을 string 형식으로 반환한다.


XHR 속성중에서 중요한 몇가지 속성

onreadystatechange
     자바스크립트 콜백함수(funtion pointer)를 저장한다.
     콜백함수는 readyState 값이 변할때 마다 호출된다.
     요청이 서버로 보내지면 readyState 는 5가지 숫자값으로 계속 변화가 일어나게 된다.

readyState
     요청의 상태를 의미한다.

     0 : UNINITIALIZED : 오브젝트는 작성되어 있으나 아직 초기화되어 있지 않다.(open()이 불리지 않았음)
     1 : LOADING : 오브젝트가 작성되었으나 아직 send()가 불리지 않았다.
     2 : LOADED : send()가 불렸지만 ststus와 header가 아직 도착하지 않았다.
     3 : INTERACTIVE : data일부를 받았다.
     4 : COMPLETED : data전부를 받았다. 완전한 데이터가 이용가능

responseText
     서버의 응답을 string 형식으로 나타낸다.

responseXML
     서버의 응답을 XML 로 나타낸다.
     이 속성은 DOM 객체로 파싱할 수 있다.

status
     서버로부터의 HTTP 상태코드이다.(예 200(OK), 404(NOT Found) 등등)

statusText
     HTTP 상태코드에 대한 텍스트 값이다.(예 OK, NOT Found 등등)

------------------------------------------------------------------------------------------
구현예제


function getHttprequest( URL, post_val )
{
 var xmlhttp = null;

try
{
 if(window.XMLHttpRequest)
 {
  xmlhttp = new XMLHttpRequest();
 }
 else
 {
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 
 var method = (post_val)? "POST":"GET";
 
 xmlhttp.open( method, URL,false);
 xmlhttp.onreadystatechange = function()
 {
  if(xmlhttp.readyState==4 && xmlhttp.status == 200 && xmlhttp.statusText=='OK')
  {
   responseText = xmlhttp.responseText;
  }
 }
 
 if( method == "POST" )
  xmlhttp.send( post_val );
 else
  xmlhttp.send('');

} catch(E)
{
 return "FALSE";
}

 return responseText = xmlhttp.responseText;
}


function BootCheck()
{
 var strCommand = "http://" + document.domain;
 strCommand +=  "/cgi-bin/Reboot";

 var post_val = "cmd=BootCheck";
 var rev_data_t = getHttprequest( strCommand , post_val);
 
 if( rev_data_t == "OK")
 {
  show_waiting(false);
  alert("REBOOT DONE!");  
  document.location.href = "/frame_intro.html";
 }

 setTimeout("BootCheck()", 1000); // 1sec unit
}

function Reboot()
{
 show_waiting(true);
 
 var strCommand = "http://" + document.domain;
 strCommand +=  "/cgi-bin/Reboot";
 
 var post_val = "cmd=Reboot";
 
 //alert(strCommand);
 var rev_data_t = getHttprequest( strCommand , post_val);
 
 if( rev_data_t != "OK")
 {
  show_waiting(false);
  alert("ERROR:: System reboot.");
 }
 
 setTimeout("BootCheck()", 1000); // 1sec
}


위 코드는 임베디드 시스템에서 웹을 통해 시스템을 리붓했을때 사용할 수 있는 루틴이다.
실제 이코드를 이용해서 시스템을 리붓한후 대기창을 뛰운다음 리붓이 다 되고나면

리붓이 끝났다는 메세지를 뛰워보일수 있다.

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 롸이언
공부 이야기/컴퓨터 몽땅 l 2008/08/25 16:06
TAG ajax, reboot

Overview

Lightbox JS is a simple, unobtrusive script used to overlay images on the current page. It's a snap to setup and works on all modern browsers.

Note: An new version of this script is available: Lightbox JS v2.0

Example

To make sense of it all, check out these examples. Click on a thumbnail or text link below:

Benefits

Places images above your current page, not within. This frees you from the constraints of the layout, particularly column widths.

Keeps users on the same page. Clicking to view an image and then having to click the back button to return to your site is bad for continuity (and no fun!).

How to Use:

  1. Include lightbox.js in your header.
    <script type="text/javascript" src="lightbox.js"></script>
    
  2. Add rel="lightbox" attribute to any link tag to activate the lightbox. For example:
    <a href="images/image-1.jpg" rel="lightbox" title="my caption">image #1</a>
    
    Optional: Use the title attribute if you want to show a caption.

Customizing:

  1. You can use CSS to style the image container. Here is the code used in the examples above:
    #lightbox{
    	background-color:#eee;
    	padding: 10px;
    	border-bottom: 2px solid #666;
    	border-right: 2px solid #666;
    	}
    #lightboxDetails{
    	font-size: 0.8em;
    	padding-top: 0.4em;
    	}	
    #lightboxCaption{ float: left; }
    #keyboardMsg{ float: right; }
    
    #lightbox img{ border: none; } 
    #overlay img{ border: none; }
  2. To create the 'shadow' effect over the page, you'll need to use a PNG file and some extra CSS. The CSS is a bit messy thanks to IE's unorthodox support of PNG transparency:
    #overlay{ background-image: url(overlay.png); }
    
    * html #overlay{
    	background-color: #000;
    	back\ground-color: transparent;
    	background-image: url(blank.gif);
    	filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="overlay.png", sizingMethod="scale");
    	}
  3. If you would like to show the user a 'loading' graphic, like the animated progress bar in the examples above, specify its location at the top of the lightbox.js file.
    var loadingImage = 'loading.gif';
  4. In the same vein, if you would like to use a 'close button', like the 'X' graphic in the examples above, specify its location at the top of the lightbox.js file.
    var closeButton = 'close.gif';	

Download:

Changelog:

1/19/06 10:40PM EST - Added keypress activated closing.
1/15/06 12:50PM EST - Added optional 'close' button.
1/10/06 10:30PM EST - Added support for captions.
12/31/05 6:00PM EST - Fixed IE6 bugs.

Modifications:

Troubleshooting:

It doesn't work at all. The image opens up in a new window.
This is commonly caused by a conflict between JS scripts. Check your body tag and look for an onload attribute. Example:
<body onload="MM_preloadImages(‘/images/menu_on.gif’)…;">
A quick fix to this problem is to append the initLightbox() to the onload attribute as so:
<body onload="MM_preloadImages(‘/images/menu_on.gif’)…;initLightbox()">
It doesn't work if I click an image before the page has finished loading.
This is not a bug, but a side-effect of unobtrusive scripts of this kind.
Flash objects appear through overlay.
Refer to comment by netasceta.
Script doesn't work with imagemaps.
Refer to comment by Jason Buechler.
Can I call the script from within a frame/iframe and still have it display on top of the entire page?
Refer to comment by Sean K. Some people have noted trouble implementing this modification. Proceed with caution, and if you can clear up the instructions it would be appreciated.
The shadow overlay doesn't stretch to cover full browser window.
Remove the default margin and padding from the body tag. Add body{ margin: 0; padding: 0; } to your stylesheet.
The shadow overlay doesn't show up in IE.
Find the filter: progid:DXI… line that you added to your stylesheet. There is a reference to the overlay.png in this line. Make sure that it is set relative to the current webpage, not relative to the CSS file.

Contact:

For discussing bugs, asking questions, and troubleshooting the script use the messageboard. Before starting a new dicussion, please do a search to see if your question has been asked and maybe answered previously. Thank you very much.

크리에이티브 커먼즈 라이선스
Creative Commons License

'공부 이야기 > 컴퓨터 몽땅' 카테고리의 다른 글

Timezone on Linux  (2) 2008/07/21
NTPClient  (0) 2008/07/20
Lightbox JS  (0) 2008/06/18
epoll 서버 샘플 프로그래밍  (0) 2008/05/29
공유메모리 관련  (0) 2008/05/18
Embedded Linux Memory SWAP 사용법  (0) 2008/05/01
Posted by 롸이언
공부 이야기/컴퓨터 몽땅 l 2008/06/18 11:05
1 

카테고리

꼭대기 (82)
롸이언 이야기 (7)
가족 이야기 (0)
친구 이야기 (1)
공부 이야기 (51)
취미 이야기 (17)
노래 이야기 (1)

달력

«   2010/03   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
Statistics Graph
tistory!get rss Tistory Tistory 가입하기! DNS Powered by DNSEver.com