본문 바로가기
PHP/PHP and AJAX

PHP AJAX Live Search 구문

by 진격의 파파 2013. 7. 23.
반응형

 

 

이번장에서는 PHP 에서 AJAX를 이용하여 Live Search 즉 실시간검색에 대해서 알아보겠습니다.   

 

여러분들이 구글이나 네이버에서  검색어를 치다보면 한글자 아니 자음 하나만 키보드를 두드려도 하단에 관련 검색어들이 뜨는것을 보았을텐데 그러한 구문과 비슷한 구문이라고 생각하면 되겠습니다.

 

 

그림처럼 "a" 라고 치면 a가 해당하는 제목을 불러와 하단에 리스팅합니다.

 

위와 같은 구문을 만들기 위해 우선 3개의 파일이 필요합니다. form 구문이 들어있는 html 또는 php 파일과 xml 파일 그리고 ajax 를 이용한 php 파일이 필요합니다.

 

xml 파일  -------- link.xml --------

<?xml version="1.0" encoding="ISO-8859-1"?>

<!-- Edited by XMLSpy® -->
<pages>
 <link>
  <title>Google</title>
  <url></url>">http://www.google.com</url>
 </link>
 <link>
  <title>Naver</title>
  <url></url>">http://www.naver.com</url>
  </link>
 <link>
  <title>Daum</title>
  <url></url>">http://www.daum.net</url>
 </link>
 <link>
  <title>Nate</title>
  <url></url>">http://www.nate.com</url>
 </link>
 <link>
  <title>Park's blog</title>
  <url></url>">http://blog.naver.com/makand123</url>
 </link>
 <link>
  <title>Zum</title>
  <url></url>">http://www.zum.com/</url>
 </link>
</pages>

// xml 파일은 원하는 내용으로 꾸며보기 바랍니다.

 

 

Form 구문이 있는 html 또는 php 파일 ------- live.html -------

<html>
 <head>
 <script>
 function showResult(str) {
 if (str.length==0) { // 검색글자의 내용이 없으면 검색 박스를 없앱니다.
   document.getElementById("livesearch").innerHTML="";
   document.getElementById("livesearch").style.border="0px";
   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("livesearch").innerHTML=xmlhttp.responseText;
     document.getElementById("livesearch").style.border="1px solid #A5ACB2";
   }
 }
 xmlhttp.open("GET","livesearch.php?q="+str,true);  // ajax 파일연동
 xmlhttp.send();
 }
 </script>
 </head>
 <body>
 

 <form> 

<!-- 텍스트 박스에 마우스 onkeyup 이벤트가 발생시 showResult() 함수로 이동하라 -->


 <input type="text" size="30" onkeyup="showResult(this.value)">
 


 <div id="livesearch"></div>
 </form>
 

 </body>
 </html>

 

 

ajax구문이 들어있는 php 파일 ------- livesearch.php -------

<?php
 $xmlDoc=new DOMDocument();
 $xmlDoc->load("link.xml");

 $x=$xmlDoc->getElementsByTagName('link');

 // q의 매개변수 값을 가져옴
 $q=$_GET["q"];

 // $q 변수값이 있는지 여부를 체크
 if (strlen($q)>0) {
 $hint="";
 for($i=0; $i<($x->length); $i++)  {
   $y=$x->item($i)->getElementsByTagName('title');
   $z=$x->item($i)->getElementsByTagName('url');
   if ($y->item(0)->nodeType==1) {
     //find a link matching the search text
     if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))  {
       if ($hint=="")   {
         $hint="<a href='" .
         $z->item(0)->childNodes->item(0)->nodeValue .
         "' target='_blank'>" .
         $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
       } else  {
         $hint=$hint . "<br /><a href='" .
         $z->item(0)->childNodes->item(0)->nodeValue .
         "' target='_blank'>" .
         $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
         }
       }
     }
   }
 }

 // 만약 xml 데이터에 검색값의 내용이 없을 경우 "no suggestion" 을 출력함
 if ($hint=="")  {
   $response="no suggestion";
 } else {
   $response=$hint;
 }

 // $response 값을 출력하라
 echo $response;
 ?>

 

이렇게 3개의 파일이 연동되면 위 그림처럼 실시간 검색의 느낌을 줄 수 있습니다. 구글, 네이버 크게 다를거 없습니다. 많이 응용해보고 멋진 소스를 개발해보기 바랍니다.

혹시 오타 또는 오류 발생시 댓글, 쪽지 주면 바로 수정해놓겠습니다.

그럼 오늘도 즐거운 하루 되세요 ^^

반응형

'PHP > PHP and AJAX ' 카테고리의 다른 글

PHP AJAX RSS Reader 구문  (0) 2013.07.24
PHP AJAX XML 연동  (0) 2013.07.22
PHP AJAX 데이터베이스 연동  (9) 2013.07.19
PHP AJAX 구문  (0) 2013.07.18