관리 메뉴

nkdk의 세상

Ajax 간단한 예제입니다 php를 이용한 우편번호 검색 본문

My Programing/AJAX

Ajax 간단한 예제입니다 php를 이용한 우편번호 검색

nkdk 2008. 3. 10. 14:08

index.php - 우편번호 입력폼이 하나 있는 페이지 입니다.(동이름을 치시면 되겠네요)  

                입력폼에서 키입력이 있을때마다 sample.php에 입력폼안의 동이름으로  

                쿼리를 실행하고, 쿼리결과를 출력합니다.  


sample.php - index.php에서 Ajax를 통해 값을받아 우편번호테이블을 이용해 결과를  

                  출력합니다.  



*********** index.php ***************  


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

<HTML>  

<HEAD>  

<META http-equiv="Content-Type" content="text/html; charset=euc-kr">  

<META http-equiv="keywords" content="">  

<META http-equiv="description" content="">  

<META http-equiv="robots" content="noindex">  

<META http-equiv="pragma" content="no-cache">  

<META http-equiv="Content-Style-Type" content="text/css">  

<META http-equiv="Content-Script-Type" content="text/javascript">  

</HEAD>  

<SCRIPT>  

    var req;//php로 보낼 request변수  

    //onkeyup 이벤트 발생시 호출되는 함수  

    function kin() {  

        req = newXMLHttpRequest(); //request 객체 생성  

        req.onreadystatechange = processReqChange;// 요청후 처리될 콜백함수를 정의합니다.  

        var kobj = document.getElementById("k"); // input Object  

        var q = kobj.value;  

        document.getElementById("out").innerText = q; // input에입력한값을 화면에표시(디버그용)  

        req.open("POST", "sample.php", true); //POST방식으로 sample.php에 요청.  

        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

         //요청헤더의 정의  

        req.send("q="+q); // sample.php에 값을 넘깁니다.  

        // 중요!!: sample.php에 값이 넘어갈때에는 UTF-8로 인코딩되어 넘어갑니다.  

    }  

//request객체생성 함수  

// function from http://www-128.ibm.com/developerworks/kr/library/j-ajax1/index.html  

function newXMLHttpRequest() {  


  var xmlreq = false;  


  if (window.XMLHttpRequest) { //파이어폭스나 맥의 사파리의 경우처리  

    // Create XMLHttpRequest object in non-Microsoft browsers  

    xmlreq = new XMLHttpRequest();  

  } else if (window.ActiveXObject) { //IE계열의 브라우져의 경우  

    // Create XMLHttpRequest via MS ActiveX  

    try {  

      // Try to create XMLHttpRequest in later versions  

      // of Internet Explorer  

      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");  

    } catch (e1) {  

      // Failed to create required ActiveXObject  

      try {  

        // Try version supported by older versions  

        // of Internet Explorer  

        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");  

      } catch (e2) {  

        // Unable to create an XMLHttpRequest with ActiveX  

      }  

    }  

  }  

  return xmlreq;  

}  


// kin()에서 정의될 콜백함수의 정의  

// function from http://developer.apple.com/internet/webcontent/xmlhttpreq.html  

// handle onreadystatechange event of req object  

function processReqChange() {  

    // only if req shows "loaded"  

    if (req.readyState == 4) {  

        // only if "OK"  

        if (req.status == 200) {  

            printData(); //kin()의 요청이 정상적으로 처리되고 출력된 값을 어떻게 처리할지의 함수  

        } else {  

            alert("There was a problem retrieving the XML data:\n" +  

                req.statusText);  

        }  

    }  

}  

//sample.php에서 출력된 내용을 어떻게 처리할것인지?  

function printData(txt) {  

    document.getElementById("serverMsg").innerHTML = req.responseText;  

}  


</SCRIPT>  

<BODY>  

<DIV id="out"></DIV>  

<INPUT type="text" autocomplete="off" value="" size="20" id="k" onkeyup="kin()">  

<DIV id="serverMsg"></DIV>  


</BODY>  

</HTML>  


***************************************  



*********** sample.php ***************  


<?php  

    $query = iconv("UTF-8","CP949",$_POST["q"]); //DB가 EUC-KR의 경우 요청값이 UTF-8로 넘어온 것을 EUC-KR로 변환  

    //$query = $_POST["q"]; // DB가 UTF-8의 경우는 그냥 받아서 처리하면됩니다.  

    $conn = mysql_connect("localhost", "root", "1111") //DB접속 정보  

    or die("connect error!!" . mysql_error());  

      

    mysql_select_db("dbname");//database명을 지정합니다  

      

    $strSQL = " SELECT sigun,dong";  

    $strSQL .= "  FROM zipcode";  

    $strSQL .= " WHERE dong like '".$query."%'";  

      

    $rs = mysql_query($strSQL);  

    while ( $row = mysql_fetch_array($rs) ) {  

        $out .= $row[0]."<BR/>";  

    }  

      

    //echo iconv("CP949","UTF-8",$out); //값이 출력될 index.php 의 인코딩이 UTF-8의 경우 변환해서 출력합니다.  

    echo $out;  

?>  


********************************