PHP 예제 - AJAX 및 XML
AJAX는 XML 파일과의 대화식 통신에 사용할 수 있습니다.
AJAX XML 예제
다음 예는 웹 페이지가 AJAX를 사용하여 XML 파일에서 정보를 가져올 수 있는 방법을 보여줍니다.
예시
CD info will be listed here...
예제 설명 - HTML 페이지
사용자가 위의 드롭다운 목록에서 CD를 선택하면 "showCD()"라는 함수가 실행됩니다. 함수는 "onchange" 이벤트에 의해 트리거됩니다.
<html>
<head>
<script>
function showCD(str)
{
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcd.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>
</body>
</html>
showCD() 함수는 다음을 수행합니다.
- CD가 선택되었는지 확인
- XMLHttpRequest 객체 생성
- 서버 응답이 준비되었을 때 실행할 함수 생성
- 서버의 파일로 요청 보내기
- URL에 매개변수(q)가 추가되었습니다(드롭다운 목록의 내용 포함).
PHP 파일
위의 자바스크립트가 호출하는 서버의 페이지는 "getcd.php"라는 PHP 파일입니다.
PHP 스크립트는 XML 문서 " cd_catalog.xml "을 로드하고 XML 파일에 대해 쿼리를 실행하고 결과를 HTML로 반환합니다.
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y=($x->item($i)->parentNode);
}
}
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
CD 쿼리가 JavaScript에서 PHP 페이지로 전송되면 다음이 발생합니다.
- PHP는 XML DOM 객체를 생성합니다.
- JavaScript에서 보낸 이름과 일치하는 모든 <artist> 요소 찾기
- 앨범 정보 출력("txtHint" 자리 표시자로 보내기)