PHP와 AJAX를 이용한 웹개발 [원문]
목차 Ajax 개요 XMLHttpRequest에 대해서 php와 Javascript에서 XML 사용하기 JSON 알아보기 php와 Ajax를 활용한 프로그램
| |||
Ajax 란 | |||
개요 1. Jesse James Garrett이 2005년 2월 ‘Ajax:A New Approach to Web Application’ 이란 에세이에서 처음으로 사용 됨. 2. Ajax는 'Asynchronous JavaScript + XML'의 줄임말 3. Ajax는 웹프로그래밍의 한 종류로 하나의 기술이 아니라 4. Ajax는 자바스크립트 렌더링 엔진을 이용한 기술
사용되는 기술에 대한 소개 XHTML (extensible hypertext markup language ) Javascript CSS (cascading style sheets ) DOM (document object model ) XML (eXtensible Markup Languag ) JSOM (JavaScript Object Notation) XmlHttpRequest
장점과 단점 장점 단점
작동 원리
| |||
| |||
XMLHttpRequest에 대해서 | |||
소개
※ 주의 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(){ var client = new XMLHttpRequest();
예제 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); }
크로스브라우징 표준웹브라우저에서 호출법 IE에서 호출법
| |||
php와 Javascript에서 XML 사용하기 | |||
php에서 사용하기 SimpleXML XML DOM
$xmlstr = << SimpleXML 이용하기
XML 문서 생성하기
XML 이용하기
DOM 이용하기 XML 문서 생성하기
javascript에서 사용하기
| |||
JSON 알아보기 | |||
경량화 데이터 교환형식 사람이 읽고 쓰기편함 기계가 해석하기 용이 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 "
}
제공되는 형태
서울지역
실행 링크 javascript:retrieveURL('http://www.superuser.co.kr/home/lib/area.php?area=서울')">
| |||
php와 Ajax를 활용한 프로그램 | |||
프로그램 시나리오 로드 이후 서버에서 환경 설정값 요청 및 받음 최근게시물 형태의 위젯의 위치 및 크기 정보 적용 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+"
}
파이어폭스에서의 마우스 드래그 앤 드랍 및 이벤트 캡쳐 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
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/
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 enterprise뭩 development 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
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
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/ [출처] [Web플밍] PHP와 AJAX를 이용한 웹개발|작성자 용이 |