'AJAX'에 해당되는 글 3건

  1. 2008.09.25 Ajax Get방식
  2. 2008.09.25 Ajax post방식
  3. 2008.09.12 우편번호 찾기
posted by 준치 2008. 9. 25. 10:22

이것은...ajax get방식으로 TotalSeach()함수를 처음에 호출을하면 SearchTxt에 있는 값을 받아오고
getXMLHttpRequest() 함수를 사용하여 XMLHttpRequest 객체를 구한다.
지역변수 httpRequest 에 넣고 MoveTotalSearch 처리 이후에 호출할 함수 선언하고 처리로직 만든다.
open(),send() 으로 실행이후에 MoveTotalSearch 함수 처리

var httpRequest = null;

function TotalSeach()
{
//debugger;
    var nowAddress = decodeURI(location.href);
    var str = document.all["SearchTxt"].value;   
   
    if(str == null || str == "")
    {
        str = "null";
    }        
    httpRequest = getXMLHttpRequest();
    httpRequest.onreadystatechange = MoveTotalSearch;
    httpRequest.open("GET",nowAddress + "?keyword=" + encodeURI(str),true);
    httpRequest.send(null);   
}

//XMLHttpRequest 객체를 구한다
function getXMLHttpRequest()
{
    if(window.ActiveXObject){
        try{
            return new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                return new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e1){
                return null;
            }
        }
    }else if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }else{
        return null;
    }
}

function MoveTotalSearch()
{
    var str = document.all["SearchTxt"].value;   
    if(str == null || str == "")
    {
        str = "null";
    }
    if(httpRequest.readyState == 4){
        if(httpRequest.status == 200){
            location.href = "이동할 URL을 넣었다";
        }else{
            alert("저장실패" + httpRequest.status);
        }
    }
}

posted by 준치 2008. 9. 25. 10:11

get방식은 써봤는데 post 방식이 안되서 과장님이 찾아주신 post 방식
보니까 소스상에서 다른점은 setRequestHeader()이게 다르더군...소스는 자바지만 함 써봅시다...ㅎㅎㅎ

// 포스트 방식
function callPostAjax() {
 var userId = document.getElementById("userId");
 var  v = userId.value;  // userID 값을 가지고 왔다.
 var url = "helloAjax.do";
 // 여러개의 파라미터 값을 넘기려면 and ~ and ~ 이런식으로 뒤에 붙여 보낸다.
 var param = "id=" + v;
 // Ajax 는 전송시 form 방식 으로 하지 않고 request에 담아서 보낸다.
 request.open("POST", url, true);
 request.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');
 request.setRequestHeader("Cache-Control","no-cache, must-revalidate");
 request.setRequestHeader("Pragma","no-cache");
 request.onreadystatechange = callback;
 request.send(param);                       

먼저 <input type="text" name="id" id="userId" onkeyup="callPostAjax();" />
바디부에서 onkeyup="callPostAjax();" 호출
GET 방식과 비교를 하여보면 get 방식에서는 url 에서 모든걸 가져갔지만
여기 POST 방식에서는 param 변수를 둬서 파라미터 값으로 가지고 가는 점이틀리다. 

그리고 EncodingFilter 에서 한글을 설정한다.
그 다음 HelloAjaxAction에서 설정

package hello;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class HelloAjaxAction extends Action {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  String id = request.getParameter("id");  
  System.out.println(id);// 콘솔창 한글 찍히나 확인용  
  String msg = "Not Okay";
  if (id.equals("test")) {
   msg = "Okay";
  }

  return new ActionForward("/hello.jsp", false);

/* config.xml 에서 설정할 것을 여기서 할 수 있는데 다음은
    Ajax 가 이런 설정을 통하여 jsp 페이지를 통째로 가져다
    쓸 수 있다는 사실을 보여준다.
*/
 }
}

posted by 준치 2008. 9. 12. 14:37

JS 로 xml 파일 읽어오는 걸 만들다 보니.. 이것저것 손대게 되네 ^^

아래는 우편번호를 찾는 것인데..

그냥 찾는게 아니라.. 특정 주소를 입력하면 onkeyup 이벤트를 통해

ActiveXObject("Msxml2.XMLHTTP") 를 생성하고.. 그곳에서 XML 값을 리턴받아서

Table 에 add 시키는 것이다..

물론 Refresh 는 없다.


이상한거는 테이블이 길어지면 보기 안좋아서.. DIV 로 스크롤 바를 줬는데

테이블 바로 위에 공백이 생긴다 -.-;


우편번호는 postman.pe.kr 에서 받았고,

커넥션 풀은 proxool 로 했다.



화면에 디스플레이 되는 JSP 파일

FileName : Register.jsp


<%@ page language="java"
 pageEncoding="euc-kr"
 import="java.sql.*"
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
 <title>My JSF 'Register.jsp' starting page</title>

 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 
<script language="javascript">

 function openDIV(divName){
 
  var obj = document.getElementById(divName);
  var x = event.clientX + parseInt(obj.offsetWidth);
  var y = event.clientY + parseInt(obj.offsetHeight);

  var _x = document.body.clientWidth - x;
  var _y = document.body.clientHeight - y;

  if(_x < 0){
   x = event.clientX + document.body.scrollLeft + x;
  }else{
   x = event.clientX + document.body.scrollLeft;
  }

  if(_y  < 0){
   y = event.clientY + document.body.scrollTop + _y + 20;
  }else{
   y = event.clientY + document.body.scrollTop;
  }

  obj.style.top = y + 30 ;
  obj.style.left = x ;
  obj.style.display = "";
 
  document.forms[0].query.focus();
 }


 function closeDIV(divName){
  var obj = document.getElementById(divName);

  if(obj.style.display != "none"){
   obj.style.display = "none";
  }
 }
 
 var req;
 
 function zipcode_check(frm){
  var inputVal = frm.query.value;

  if(inputVal.length < 2){
   return;
  }
   
  req = new ActiveXObject("Msxml2.XMLHTTP");
  if(req){
   req.onreadystatechange = processStateChange;  
   req.open("GET", "SearchAddr.jsp?dong=" + inputVal, false);
   req.send();
  } 
 }
 
 function processStateChange(){
  if(req.readyState == 4){
   if(req.status == 200){
    var nodes = req.ResponseXML.selectNodes("//addr");
    FillNodes(nodes);    
   }else{
    alert("Ooops : " + req.statusText);
   }
  } 
 }
 
 // XML 을 읽어들여서 테이블에 채운다.
 function FillNodes(nodes){
  var tableObj = document.getElementById("addrTbl");
  var tableBody = tableObj.childNodes[0];
  var tableRow, tableCell;
 
  if(tableObj.rows.length > 0){
   for(var i = 0; i < tableObj.rows.length; i++){
    tableObj.deleteRow(i);
   }
  }

  for(var i = 0; i < nodes.length; i++){

   var st = nodes[i].selectSingleNode("zipcode").text + " "
      + nodes[i].selectSingleNode("sido").text + " "
      + nodes[i].selectSingleNode("gugun").text + " "
      + nodes[i].selectSingleNode("dong").text + " "
      + nodes[i].selectSingleNode("ri").text + " "
      + nodes[i].selectSingleNode("bunzi").text;
     
   tableRow = document.createElement("TR");
   tableBody.appendChild(tableRow);
   tableCell = document.createElement("TD");
   tableRow.appendChild(tableCell);
   tableRow.runtimeStyle.cursor = "hand";  
   tableCell.innerHTML = st;
  }

  document.getElementById("addrTbl").ondblclick = SelectTR;
 
 }
 
 function SelectTR(element){
  var row ;
 
  if(element == null){
   element = window.event.srcElement;
  }
 
  row = findRow(element);
 
  AddrSelect(element.innerHTML);
 
 
 }
 
 function findRow(element){
  if(element.tagName == "TR"){
   return element;
  }else{
   return null;
  }
 }
 
 function AddrSelect(addr){
  document.forms[0].addr.value = addr;
  closeDIV('FindZipCodePanel');
 }

</script>
</head>
 
 <form name="registerForm" >
<table border="1" align="center" width="500" >
 <tr>
  <td>우편번호 :
   <input type="text" id="zip1" name="zip1" readonly size="3" /> -
   <input type="text" id="zip2" name="zip2" readonly size="3" />
   <input type="button" id="FindZipCodeBtn" name="FineZipCodeBtn" value="우편번호 찾기" onclick="openDIV('FindZipCodePanel')" />
  </td>
 </tr>
 <tr>
  <td>주 소 : <input type="text" id="addr" name="addr" readonly size="40" /></td>
 </tr>
 <tr>
  <td>상세 주소 : <input type="text" id="addrDetail" name="addrDetail" size="40" /></td>
 </tr>
</table>

<DIV id="FindZipCodePanel" style="POSITION: absolute; Display:none; BACKGROUND-COLOR: white; WIDTH:500PX; BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid;BORDER-LEFT: gray 1px solid; BORDER-BOTTOM: gray 1px solid; ">

<TABLE width="100%" align="center" border="1" cellpadding="0" cellspacing="0">
 <TR>
  <TD align="right" bgColor="#D7DED6" height="13"><a href="javascript:closeDIV('FindZipCodePanel');">X</a></TD>
 </TR>
 <TR>
  <TD>주소를 입력하세요</TD>
 </TR>
 <TR>
  <TD><input type="text" name="query"  onkeyup='zipcode_check(this.form)' ondblclick=""/></TD>
 </TR>
 <TR>
  <TD><div id="addrTableDIV" style="OVERFLOW-Y:scroll;WIDTH:100%;POSITION:relative;HEIGHT:200px;BORDER-TOP: gray 1px solid;">
   <table id="addrTbl" border="1" align="center" width="100%" ></table></div></TD>
 </TR>  
</TABLE>  

</DIV>


<body>


</body>
</html>


Query String 을 통해 xml 형식으로 주소를 넘겨주는 JSP 파일

FileName : SearchAddr.jsp



<?xml version="1.0" encoding="ksc5601"?>
<Address>
<%@ page language="java"
 contentType="text/xml; charset=euc-kr"
 import="java.sql.*"
%><%

 request.setCharacterEncoding("euc-kr");
 
 String dong = request.getParameter("dong");
 
 if(dong == null){
  return;
 }
 
 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 
 try{
 
  conn =  DriverManager.getConnection("proxool.AjaxSample");
  stmt = conn.createStatement();
 
  String query = "select * from zipcode where dong like binary '%" + dong + "%'";
 
  rs = stmt.executeQuery(query);
 
  while(rs.next()){
%>
<addr>
<zipcode><%= rs.getString("zipcode") %></zipcode>
<sido><%= rs.getString("sido") %></sido>
<gugun><%= rs.getString("gugun") %></gugun>
<dong><%= rs.getString("dong") %></dong>
<ri><%= rs.getString("ri") %></ri>
<bunzi><%= rs.getString("bunzi") %></bunzi>
<seq><%= rs.getString("seq") %></seq>
</addr>
<%    
  }
 
 rs.close();
 }catch(Exception e){
  e.printStackTrace();
 }finally{
  if(stmt != null) stmt.close();
  if(conn != null) conn.close();
 }
%></Address>