최신 웹 개발 튜토리얼
 

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;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.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를 객체를 생성
  • 서버 응답이 준비되었을 때 실행되는 함수를 만듭니다
  • 서버에 파일로 요청을 보내기
  • 매개 변수 것을 알 (q) (드롭 다운 목록의 내용)를 URL에 추가

PHP 파일

위의 자바 스크립트에 의해 호출 된 서버의 페이지라는 PHP 파일입니다 "getcd.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를 쿼리가 PHP 페이지에 자바 스크립트에서 전송하면, 다음과 같은 일들이 일어난다 :

  1. PHP는 XML DOM 객체를 생성
  2. 모든 찾기 <artist> 자바 스크립트에서 보낸 이름과 일치하는 요소를
  3. 앨범 정보가 출력 (send to the "txtHint" placeholder)