간단한 관련예제 달라시는분이 상당히 계셔서
일일히 보내드리지 못해 여기를 빌려올립니다.
나름데로 주석을 달아놨으니 참고하세요.
내용은 화일 두개입니다.
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;
?>
********************************
일하는중에 올리는 것이라 설명이 부족합니다.
성격에 맞지 않는다면 며칠 후 삭제하겠습니다.
우편번호 테이블은 스쿨 자료실에서 구하시면 됩니다.
출처 : Tong - 드렁크수달스님의 ■ AJAX ■통
"쇼핑몰·홈페이지·오픈마켓
블로그·페이스북·이메일 등의 각종 마케팅 글쓰기, 각종 광고, 영업, 판매, 제안서, 전단지 반응율 3배×10배 이상 높이는 마법의 8단계 공식" |
☞자세히보기 |
|
|