2014년 7월 23일 수요일

자동완성 기능 구현하기(Ajax 예제)[제이쿼리/아작스/jQUERY교육/Ajax교육/jquery/ajax/강좌/교육/구로디지털단지제이쿼리/JavaScript/HTML/HTML5/자바스크립트/교육잘하는곳]

자동완성 기능은 Google Suggest 에서 가장 먼저 구현하였다그 후 국내에는 네이버를 필두로 지금은 거의 모든 포탈업체의 검색창에는 자동완성 기능이 구현되어 있다.  
 
 
var AutoComplete = {
        xmlHttp : null,
        
        ContentLoader: function(url, execFunction) {
                 xmlHttp = this.getXMLHttpRequest();
                 xmlHttp.onreadystatechange = execFunction;
                 xmlHttp.open("POST", url, true); // url의 주소를 GET방식으로 열 준비를 한다.
                xmlHttp.send(); //서버에 전송한다.
        },
        
        getState: function() {
                if(xmlHttp.readyState == 4){ //데이터의 전부를 받은 상태
                        if(xmlHttp.status == 200){//요청 성공
                                   return true;
                          }else{
                                  return false;
                        }
                }
        }
}
 

package web.ajax;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.*;
import com.opensymphony.xwork2.ActionSupport;
public class AjaxAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
        private HttpServletRequest request;
        private HttpServletResponse response;
    private Logger logger = Logger.getLogger(this.getClass());
   public String autoComplete() throws Exception {
            try{
                    logger.info("autoComplete start");
 

String[] wordArr = {"acrobat“,                                                "adobe“,                                                "bmw",
                                                "brave“,                                                "cbs“,                                                "cnn",
                                                "heaven“,                                                "html“,                                                "kbs",
                                                "key“,                                                "net“,                                                "news",
                                                "queen“,                                                "quick“,                                                "soup",
                                                "super“,                                                "ufo“,                                                "usb",
                                                "work“,                                                "wow“,                                                "zebra",
                                                "zenith"};
                    StringBuffer xmlStr = new StringBuffer("");
                    boolean isTitleExist = false;
                    //실제업무에서는 비지니스 레이어에서 XML String을 구현한다.
                    //String xmlStr = ajax.getAutoCompleteTitleList(boardVO);
                    xmlStr.append("<?xml version=\"1.0\" encoding=\"EUC-KR\"?>");
                    xmlStr.append("<words>");
for(int i = 0;  i < wordArr.length ; i++){
                            if(wordArr[i].indexOf(request.getParameter("word")) != -1){
                                    xmlStr.append("<word>");
                                    xmlStr.append(wordArr[i]);
                                    xmlStr.append("</word>");
                                    isTitleExist = true;
                            }
                    }

xmlStr.append("</words>");
                    //logger.info("request.getParameter(\"title\") : " + request.getParameter("title"));
                    logger.info("xmlStr.toString() : " + xmlStr.toString());
                    if(isTitleExist){
                            response.setContentType("text/xml");
                        response.setHeader("Cache-Control", "no-cache");
                        response.getWriter().write(xmlStr.toString());
                    }else{
                            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                    }
                    logger.info("forward :" + request.getParameter("forward"));
                    logger.info("autoComplete end");
                    return null;
            }catch(Exception e){
                        logger.info("Error : " + e.toString());
                        e.printStackTrace();
                        throw e;
                }    }
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
        public void setServletResponse(HttpServletResponse response) {
                this.response = response;
        }
}
 
[AutoComplete.jsp]
<%@ page contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<title>autoComplete</title>
<script type="text/javascript" src="ajax.js"></script>
<script>
        var div;
        var table;
        var text;
        
        function onLoad(){
                div = document.getElementById("autoCompleteDiv");
                table = document.getElementById("autoCompleteTable");
                text = document.getElementById("autoCompleteText");
        }
        
        function listAutoComplete(){
                if(text.value != ""){
                        if(event.keyCode != 229){

                                var url = "autoComplete.action?word=" + text.value;
                                AutoComplete.ContentLoader(url, viewTitleList);
                        }
                }else{
                        clearTitleList();
                }
        }

        function viewTitleList(){
                clearTitleList();
                if(AutoComplete.getState()){ //데이터의 전부를 받은 상태
                        var tr, td;
                        var words = xmlHttp.responseXML.getElementsByTagName("word");
                        var size = words.length;
                        for(var i = 0 ; i < size ; i++){
                                tr = table.insertRow();
                                tr.style.width = "100%“;
                                td = tr.insertCell();
                        td.style.width = "100%";
                        td.style.cursor = "hand";
                        td.innerText = words[i].firstChild.nodeValue;
                                td.onclick = function() { wordClick(this);};
                        td.onmouseover = function() { mouseOver(this);};
                                td.onmouseout = function() { mouseout(this);};
                        }
                }
        }


        function clearTitleList(){
                var ind = table.rows.length;
        for (var i = ind - 1; i >= 0 ; i--) {
            table.deleteRow(i);
        }
        }
        
        function wordClick(oTd){
                text.value = oTd.innerText;
        }
        
        function mouseOver(td){
                td.style.background= "#CBE7BA“;
        }

        function mouseout(td){
                td.style.background= "#FFFFFF“;
        }
</script>
</head>
<body onLoad="onLoad()">
<input type="text" id="autoCompleteText" style="width:200px" autocomplete="off" onkeyup="javascript:listAutoComplete()"><br>
<div id="autoCompleteDiv" style="position:absolute; width:200px; height:180px; scrolling:yes; overflow-y:auto;">
        <table id="autoCompleteTable" style="width:100%"></table>
</div>
</body>
</html>
 
 
 

오라클자바커뮤니티교육센터, 개발자전문교육, 개인80%환급 
www.oraclejavacommunity.com


평일주간(9:30~18:10) 개강
(7/28)[기업100%환급]C#4.0,WinForm,ADO.NET프로그래밍
(7/28)[기업100%환급]안드로이드개발자과정
(8/04)[기업100%환급]자바기초에서 JDBC, Servlet/JSP까지 
(8/04)[기업100%환급]PL/SQL,ORACLE HINT,TUNING
(8/08)[기업100%환급]SQL기초에서 Schema Object까지
(8/08)[기업100%환급]Spring ,MyBatis,Hibernate실무과정
(8/11)[채용예정교육]오라클자바개발잘하는신입뽑기프로젝트,교육전취업확정

평일야간(19:00~21:50) 개강
(7/24)SQL기초에서실무까지
(7/29)안드로이드개발자과정
(7/29)Spring3.X, MyBatis, Hibernate실무과정
(8/04)웹퍼블리싱 마스터
(8/05)JSP,Ajax,jQUERY,Spring,MyBatis,Hibernate속성과정
(8/08)닷넷(C#,Network,ADO.NET,ASP.NET)마스터과정
(8/28)자바기초에서JSP,Ajax,jQuery,Spring3.2,MyBatis까지

주말(10:00~17:50) 개강
(7/26)Spring3.X, MyBatis, Hibernate실무과정
(7/26)개발자를위한PLSQL,SQL튜닝,힌트
(8/02)C#,ASP.NET마스터
(8/02)웹퍼블리싱 마스터
(8/02)SQL초보에서 Schema Object까지
(8/09)안드로이드개발자과정
(8/09)자바기초에서JSP,Ajax,jQuery,Spring3.2,MyBatis까지
(8/23)JAVA,Network&WEB&Framework(자바기초에서웹스프링까지)

주말저녁(18:30~22:20) 개강
(8/02)JAVA,Network&WEB&Framework
(8/09)SQL기초에서실무까지

댓글 없음:

댓글 쓰기