[Web플밍] PHP와 AJAX를 이용한 웹개발

|

PHPAJAX를 이용한 웹개발 [원문]

 

목차

Ajax 개요    
    Ajax

    
사용되는 기술에 대한 소개
    Ajax
의 장점과 단점
    
작동원리

XMLHttpRequest에 대해서
    
소개
    
레퍼런스
    
사용법
    
크로스브라우징

phpJavascript에서 XML 사용하기
    php
에서 XML사용하기
    Javascript
에서 XML 사용하기 

JSON 알아보기 

phpAjax를 활용한 프로그램

 

Ajax

개요

1. Jesse James Garrett20052월 ‘Ajax:A New Approach to Web Application’ 이란 에세이에서 처음으로 사용 됨

2. Ajax'Asynchronous JavaScript + XML'의 줄임말
    '
비동기  자바스크립트 XML‘ 

3. Ajax는 웹프로그래밍의 한 종류로 하나의 기술이 아니라
    
여러 가지 기술이 복합된 방법론  

4. Ajax는 자바스크립트 렌더링 엔진을 이용한 기술

 

사용되는 기술에 대한 소개

XHTML (extensible hypertext markup language )
        
하이퍼텍스트 생성 언어(HTML) 버전 4를 확장성 생성 언어(XML)를 적용하여 재구성한 것.

Javascript
미국의 넷스케이프커뮤니케이션사가 개발한 스크립트 언어.  

CSS (cascading style sheets )
        
하이퍼텍스트 생성 언어(HTML) 문서의 형태를 기술하기 위한 시트.  

DOM (document object model )
        
웹 브라우저를 통한 확장성 생성 언어(XML) 문서의 상호 연동을 위한

        
객체 기반의 문서 모델.

XML (eXtensible Markup Languag )
          
하이퍼텍스트 생성 언어(HTML)를 대체할 목적으로 월드 와이드 웹 컨소시엄(W3C)

          
표준화 작업을 진행한 페이지 기술 언어.

JSOM (JavaScript Object Notation)
         
경량화 데이터 교환형식

XmlHttpRequest
         
서버로 비동기 호출을 할 수 있음

 

장점과 단점

장점
          ActiveX
나 플래쉬를 상당부분 대체가능
          
페이지가 로드된 후 페이지를 동적으로 변화시키는 것에 적합
          
원하는 응답을 빠른 시간에 받을  수  있음
          
서버의 부하를 줄일수 있음
          
브라우져에 종속되지 않음

단점
          
리플래쉬시 모든정보가 사라짐
          
뒤로가기 버튼을 사용할 수 없음
          
즐겨찾기를 할 수 없음
          
디버깅이 어려움
          
클라이언트 에서 많은 로직이 처리되어야 함

 

작동 원리

    

 

     

 

XMLHttpRequest에 대해서

소개

  1. XMLHttpRequest는 로딩이 완료된 웹 페이지에서 자바스크립트 렌더링 엔진을 이용하여 다시 서버에 자료를 보내거나 받아오는 것을 가능 

  2. XML 이외의 다른 형태의 자료도 지원한 

  3. Javascript 렌더링 엔진을 이용함으로 브라우저에 종속되지 않음 

주의

XMLHttpRequest는 서로 다른 도메인에서는 작동되지 않음
    -
대부분의 브라우저에서는 요청후 중지되나 인터넷 익스플러러에서는
       
보안 경고 창이 나타나 사용자가 선택가능

래퍼런스

표준 매소드

abort()

현재의 요청

getAllResponseHeaders()

HTTP요청에 대한 모든 헤더를 키/값으로 반환한다.

getResponseHeader("header")

명시된 헤더의 문자열값을 반환

open("method","url")

서버 호출단계 "method" 아규먼트는 GET,POST,HEAD하나이고 URL아규먼트는 상대혹은 절대주소가 들어간다.

send(content)

요청을 서버로 보낸다.

setRequestHeader("Header","value")

명시된 값으로 헤더를 설정한다. 헤더에 값을 설정하기 전에는 반드시 open()메소드를 호출한다.

표준 프로퍼티

onreadystatechange

상태에 변경이 있을때 마다 실행되는 이벤트 핸들러

readyState

XMLHttpRequest가 요청한 상태를 반환

(0:초기화, 1: 로드중, 2: 로드됨, 3:처리중, 4:완료됨)

responseText

XMLHttpRequest 의 서버의 응답이 문자열로 됨

responseXML

XMLHttpRequest 의 서버의 응답이 XML로 됨,

파싱가능, DOM객체로 처리된다.

status

서버로 부터 받은 HTTP상태코드

(정상:200, 비정상:404(Page Not Found))

statusText

Http상태코드의 텍스트 버전(정상, 오류)

 

사용법

예제 1......

GET 방식으로 서버에 요청하기 

간당하게 XML파일을 가져오는 예제  

function handler(){
    if (req.readyState == 4) {
        if (req.status == 200) {
            if(this.responseXML != null)
                alert(this.responseXML.getElementById('test').firstChild.data );
            else
                alert(“None”);
          } else {
                alert("Problem: " + req.statusText);
          }
    }

var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();

 

예제 2......

POST 방식으로 서버에 요청하

function handler(){

    if (req.readyState == 4) {

        if (req.status == 200) {

            if(this.responseXML != null)

                alert(this.responseXML.getElementById('test').firstChild.data );

            else

                alert(“None”);

        } else {

                alert("Problem: " + req.statusText);

          }

    }

}

function ping(message) {

    var client = new XMLHttpRequest();

    client.onreadystatechange = function()

    client.open("POST", "/test.php");

    client.send(message);

}

 

크로스브라우징

표준웹브라우저에서 호출법
    var client = new XMLHttpRequest();
    client.onreadystatechange = handler;
    client.open("GET", "test.xml");
    client.send();

IE에서 호출법
    var client = new ActiveXObject("Microsoft.XMLHTTP");
    client.onreadystatechange = handler;
    client.open("GET", "test.xml");
    client.send();

 

phpJavascript에서 XML 사용하기

 

php에서 사용하기

SimpleXML
    SimpleXML
모듈은 사용자가 쉽게 XML문서를  객체화 시켜 사용 가능

    
요구사항 : PHP5    

XML
    James Clark
expat를 사용
.
    XML
문서를 처리할 수 있게 하지만, 유효성을 검증하지는 않음

    
요구사항 : PHP를 아파치 1.3.9 이상의 모듈로 컴파일
               expat
설치 => http://www.jclark.com/xml/expat.html

DOM
    XML
문서를 DOM API 로 제공함

    
요구사항 : java VM이 설치 되어있어야 함 (java VMJNI 생성하여 사용)

 

$xmlstr = <<
 
  
  
   
   Ms. Coder
   Onlivia Actora
   

   
   Mr. Coder
   
El Act'r
   
  

  
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  

  7
  5
 


XML;

SimpleXML 이용하기

 가져오기
$xml = simplexml_load_string($xmlstr);
echo $xml->movie[0]->plot;

 

XML 문서 생성하기
$xml = simplexml_load_string("");
$xml->movie->actor->age = '21';
echo $xml->asXML();

 

XML 이용하기

 가져오기
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xmlstr, $vals, $index);
xml_parser_free($xml_parser);
$key=$index[PLOT][0];
echo $vals[$key][value];

 

DOM 이용하기
 
가져오기
$doc = new DOMDocument();
$doc->loadXML($xmlstr);
$allnodes = $doc->getElementsByTagName('plot');
$node = $allnodes->item(0);
echo $node->nodeValue;

XML 문서 생성하기
$doc = new DOMDocument("1.0", "UTF-8");
$root = $doc->createElement("movies");
$root = $doc->appendChild($root);
$elementname = $doc->createElement("movie");
$elementname = $root->appendChild($elementname);
$elementname1 = $doc->createElement("actor");
$elementname1 = $elementname->appendChild($elementname1);
$elementname2 = $doc->createElement("actor");
$elementname2 = $elementname1->appendChild($elementname2);
$elementname2->appendChild($doc->createTextNode("29"));

 

javascript에서 사용하기


:badtag -->

XMLHTTP


XML  읽어오기

 

 

JSON 알아보기


JSON
(JavaScript Object Notation)

    경량화 데이터 교환형식

    사람이 읽고 쓰기편함

    기계가 해석하기 용이
    
언어로부터 완벽하게 독립

JSON의 구조

    name/value 형태의 쌍으로 collection 타입

    값들의 순서화된 리스트

 

 

 

 

 

 

 

 기 본 예 제

 Javascript part

    



PHP part


    include ib/lib.php";

    $sql = "SELECT name FROM list WHERE `area`='".$_REQUEST[area]."' order by rand() LIMIT 9";

    $query = $db->query($sql,"su_member");

    while($data = mysql_fetch_array($query)){

     echo "

  • ". $data[name]n";

        }


    제공되는 형태


        서울지역

        

  • 정우천

        

  • 이인성

        

  • 정명재

        

  • 정봉수

        

  • 윤동순

        

  • 유종훈

        

  • 노권수

        

  • 오정석

        

  • 김정석


    실행 링크

        javascript:retrieveURL('http://www.superuser.co.kr/home/lib/area.php?area=서울')">





  •  phpAjax를 활용한 프로그램

     

    프로그램 시나리오

        로드 이후 서버에서 환경 설정값 요청 및 받음

        최근게시물 형태의 위젯의 위치 및 크기 정보 적용

        Javascript를 이용하여 브라우져의 이벤트 캡쳐

        위젯이 drag & drop으로 위치 이동 가능

        최종 이동위치에 대한 좌표값 축출

        축출된 좌표값을 서버로 전송

        전송된 좌표값 DB에 저장

        새로 지정된 좌표값 클라이언트에 전송

        전송받은 값으로 레이어 위치 재정렬






    환경설정

    소스

    include_once "../lib/json.php";

    include_once "../lib/db.config.php"

    $query = mysql_query("select * from myp where cid='locli' order by no");

    $i=0;

    while($data = mysql_fetch_array($query)){

    $count=count($ENVS[$data[gid]]);

    $ENVS[$data[gid]][$count] = array('width'=>$data[width],'height'=>$data[height],'xpos'=>$data[xpos],'ypos'=>$data[ypos],'names'=>$data[names]);

    }

    $JSON = new Services_JSON();

    echo $JSON->encode($ENVS);

    ?>


    리턴 파일 형식

    {"data":

    [

    {"idx":"locli.search.linux",

    "link":"/home/lecture/index.php?cateNo=&secNo=&theNo=&leccode=36",

    "subject":"u2592 5. RedHat 9 (APM(Apache Php Mysql) uc124uce58 ubc0fuc6b4uc601)"}

    ,{"idx":"locli.search.linux",

    "link":"/home/lecture/index.php?cateNo=&secNo=&theNo=&leccode=33",

    "subject":"u2592 2. RedHat 9 uc124uce58ud6c4 uae30ubcf8 uc14bud305"}

    ,{"idx":"locli.search.linux"

    ,"link":"/home/lecture/index.php?cateNo=&secNo=&theNo=&leccode=788",

    "subject":"APM uc124uce58 ubc0f uc124uc815(1.3.9)"}

    ,{"idx":"locli.search.linux",

    "link":"/home/lecture/index.php?cateNo=&secNo=&theNo=&leccode=32",

    "subject":"u2592 1. Redhat 9 uc124uce58(2/2)"}

    ,{"idx":"locli.search.linux",

    "link":"/home/lecture/index.php?cateNo=&secNo=&theNo=&leccode=5",

    "subject":"u2592 1. RedHat 9 uc124uce58(1/2)"}

    ]

    }

    서버에 환경 설정 요청


    function createXMLHttp(str){

    if(window.ActiveXObject){

    if(!str) xmlHttp = new ActiveXObject("Microsoft.XMLHttp");

    }else if(window.XMLHttpRequest){

    if(!str) xmlHttp = new XMLHttpRequest();

    }

    }


    function getENV(){

    url = 'runMy/Env.php';

    //url="XMLSchema/env.xml";

    createXMLHttp();

    xmlHttp.open("POST",url,true);

    xmlHttp.onreadystatechange = setENV;

    xmlHttp.send(null);

    }


    function setENV(){

    if(xmlHttp.readyState == 4){

    if(xmlHttp.status == 200){

    var results = xmlHttp.responseText;

    var obj = results.parseJSON();

    for(i=0;i

    inputENV(obj.search[i],'search');

    }

    }

    }

    }


    function inputENV(obj,str){

    document.getElementById('hiddenLayer').innerHTML=document.getElementById('hiddenLayer').innerHTML+"


    "+obj.names+"
    ";


    }









    파이어폭스에서의 마우스 드래그 앤 드랍 및 이벤트 캡쳐

    document.captureEvents(Event.MOUSEDOWN);

    document.onmousedown=mousdownMo;

    document.captureEvents(Event.MOUSEMOVE);

    document.onmousemove = moveing

    document.captureEvents(Event.MOUSEUP);

    document.onmouseup = mousupMo;



    function mousdownMo(event){

    if (event.which !=1){

    return false;

    }else{

    if(event.target.className == "drag") {

    mousdown = true;

    x = event.clientX;

    y = event.clientY;

    }

    }

    }

    function mousupMo(event) {

    mousdown = false;

    }

    function moveingMo(event) {

    if(mousdown) {

    var distX = event.clientX - x;

    var distY = event.clientY - y;

    event.target.style.left =parseInt(event.target.style.left) + distX;

    event.target.style.top = parseInt(event.target.style.top) + distY;

    x = event.clientX;

    y = event.clientY;

    return false;

    }

    }



    Internet Explorer에서의 마우스 드래그 앤 드랍 및 이벤트 캡쳐


    document.onmousedown = mousdownIe;

    document.onmouseup = mmousupIe;

    document.onmousemove = moveingIe;



    function mousdownIe() {

    if(event.srcElement.className == "drag") {

    mousdown = true;

    x = event.clientX;

    y = event.clientY;

    }

    }

    function mousupIe() {

    mousdown = false;

    }

    function moveingIe() {

    if(mousdown) {

    var distX = event.clientX - x;

    var distY = event.clientY - y;

    event.srcElement.style.left =parseInt(event.srcElement.style.left) + distX;

    event.srcElement.style.top = parseInt(event.srcElement.style.top) + distY;

    x = event.clientX;

    y = event.clientY;

    return false;

    }

    }



    .drag { position: absolute; cursor:move }






    Javascript Part


    function setpos(xpos,ypos,idx){

    if(idx != ""){

    url = 'runMy/setpos.php?xpos='+xpos+'&ypos='+ypos+'&idx='+idx; xmlHttp='';

    createXMLHttp();

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

    xmlHttp.onreadystatechange = setpost;

    xmlHttp.send(null);

    }

    }


    function setpost(){

    if(xmlHttp.readyState == 4){

    if(xmlHttp.status == 200){

    ..

    }else{

    alert(xmlHttp.responseText);

    }

    }

    }



    PHP Part


    $data = explode(".",$_REQUEST[idx]);


    mysql_connect("localhost","su","dlfmsdkcla");

    mysql_select_db("test");


    mysql_query("update myp set xpos=".$_REQUEST[xpos].",ypos=".$_REQUEST[ypos]." where cid='".$data[0]."' AND gid='".$data[1]."' AND names='".$data[2]."'");


    if(mysql_error()){

    echo "500";

    }else{

    echo "ok";










     PHP based Ajax Frameworks

     AjaxAC

    AjaxAC is an open-source framework written in PHP, used to develop/create/generate AJAX applications. The fundamental idea behind AJAX (Asynchronous JavaScript And XML) is to use the XMLHttpRequest object to change a web page state using background HTTP sub-requests without reloading the entire page.

    Homepage: http://ajax.zervaas.com.au

     

    XOAD

    XOAD, formerly known as NAJAX, is a PHP based AJAX/XAP object oriented framework that allows you to create richer web applications.

    Homepage: http://www.xoad.org
    Documentation:
    http://www.xoad.org/documentation/source/
    Demo: http://www.xoad.org/examples/

     

    PAJAJ

    What is the PAJAJ framework, it stands for (PHP Asynchronous Javascript and JSON). It is a object oriented Ajax framework written in PHP5 for development of event driven PHP web applications.

    Homepage: http://sourceforge.net/projects/pajaj/
    Documentation: http://www.wassons.org/pajaj/public/docs/index.php

     

    Symfony

    A PHP 5 Development Framework inspired by Rails. It has integrated database abstraction and support for AJAX. Installation is fairly easy. Symfony is aimed at building robust applications in an enterprise context. This means that you have full control over the configuration: from the directory structure to the foreign libraries, almost everything can be customized. To match your enterprisedevelopment guidelines, symfony is bundled with additional tools helping you to test, debug and document your project.

    AjaxBlog: http://ajaxblog.com/arc.application-in-php-in-minutes-with-symfony

    Homepage: www.symfony-project.com
    Documentation:
    http://www.symfony-project.com/content/documentation.html
    http://www.symfony-project.com/trac/wiki 



    XAJAX

    xajax is an open source PHP class library that allows you to easily create powerful, web-based, Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page.

    Homepage: http://xajax.sourceforge.net/

     

    PEAR:: HTML_AJAX

    Provides PHP and JavaScript libraries for performing AJAX (Communication from JavaScript to your server without reloading the page)

    Homepage: http://pear.php.net/package/HTML_AJAX
    Documentation: http://pear.php.net/package/HTML_AJAX/docs

     

    Flexible AJAX

    Flexible Ajax is a handler to combine the remote scripting technology, also known as AJAX (Asynchronous Javascript and XML), with a php-based backend.

    Homepage: http://tripdown.de/flxajax/
    Demo: http://tripdown.de/flexible_ajax_example.php

    http://blog.naver.com/limhy0128/60032877868 


    And