1. 연관검색어 기능 


-검색어를 입력하면 keyup이 될 때마다 맞는 검색어가 밑에 링크로 뜬다.

링크를 누르면 inputbox안에 value가 들어간다.


-suggestClient.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    .suggest{
        display: none;
        position: absolute;
        left:11px;
        top:131px;
    }    
</style>
<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>
<script type="text/javascript">
 
    //inputbox에 keyup될때마다 호출
    function sendKeyword(){
        
        var userKeyword=document.myForm.userKeyword.value;
        
        //아무것도 없을때 결과창을 숨긴다.
        if(userKeyword==""){
            hide();
            return;
        }
        
        var params="userKeyword="+userKeyword;
        
        sendRequest("suggestClient_ok.jsp", params, displaySuggest, "POST");
    }
    
    function displaySuggest(){
        
        if(httpRequest.readyState==4){
            if(httpRequest.status==200){
                
                //5|abc,ajax,abc마트 값이 여기로 들어옴
                var resultText=httpRequest.responseText;
                
                var resultArray=resultText.split("|");
                
                //검색창 결과 갯수
                var count=resultArray[0];
                
                //alert(count);
                
                var keywordList=null;
                
                if(count>0){
                    keywordList=resultArray[1].split(",");
                    
                    var html="";
                    
                    for(var i=0;i<keywordList.length;i++){
                        //select호출
                        html += "<a href=\"javascript:select('" +
                                keywordList[i] + "');\">" +
                                keywordList[i] + "</a><br/>";
                        //<a href="javascript:select('ajax');">ajax</a><br/>
                        
                    }
                    var suggestListDiv=document.getElementById("suggestListDiv");
                    suggestListDiv.innerHTML=html;
                    show();
                    
                }else{
                    //count==0
                    hide();
                }
                
            }else{
                //status!=200
                hide();
            }
            
        }else{
            //readystate!=4
            hide();
        }
        
        
    }
    
    //사용자가 제시어에서 클릭한 키워드
    function select(selectKeyword){
        //클릭한 제시어를 inputbox에 넣어줌
        document.myForm.userKeyword.value=selectKeyword;
        hide();
    }
    
    function show(){
        var suggestDiv=document.getElementById("suggestDiv");
        suggestDiv.style.display="block";//보여짐
    }
    
    function hide(){
        var suggestDiv=document.getElementById("suggestDiv");
        suggestDiv.style.display="none";//숨김
    }
    
    window.onload=function(){
        hide();    
    }
    
</script>
</head>
<body>
<h1>제시어</h1>
<hr/>
<br>
<form action="" name="myForm">
<input type="text" name="userKeyword" onkeyup="sendKeyword();"/>
<input type="button" value="검색"/>
 
<div id="suggestDiv" class="suggest">
    <div id="suggestListDiv"></div>
</div>
</form>
</body>
</html>
cs



-suggestClient_ok.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Collections"%>
<%@page import="java.util.List"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
 
<%!
    String[] keywords={"ajax","Ajax","Ajax 실전 프로그래밍",
        "AZA","AZERA","자수","자전거","자바 프로그래밍",
        "자바 서버 페이지","자바캔","ABC마트","APPLE"
    };
 
    public List<String> search(String userKeyword){
        if(userKeyword==null||userKeyword.equals("")){
            return null;
            //이것도 가능
            //return Collections.EMPTY_LIST;
        }
        
        //userKeyword=userKeyword.toUpperCase();//대문자 검색
        
        List<String> lists=new ArrayList<String>();
        
        for(int i=0;i<keywords.length;i++){
            if(keywords[i].startsWith(userKeyword)){
                lists.add(keywords[i]);
            }
        }
        return lists;
    }
%>
 
<%
    String userKeyword=request.getParameter("userKeyword");
 
    List<String> keywordList=search(userKeyword);
    
    out.print(keywordList.size());
    
    out.print("|");
    
    Iterator<String> it=keywordList.iterator();
    
    while(it.hasNext()){
        String value=(String)it.next();
        
        out.print(value);
        
        //마지막에는 쉼표 안찍게
        if(keywordList.size()-1>0){
            out.print(",");
        }
    }
    
    //5|abc,ajax,abc마트
%>
 
cs



-실행화면



2. HTML DOM 객체를 이용한 노드 추가, 제거 

- 버튼을 누르면 노드를 추가하고 삭제할 수 있다.

이를 응용하면 파일을 추가하고 삭제하는 기능들을 만들 수 있다.


-DOM 객체 트리


- book 노드의 입장에서 firstChild는 title 노드가 되며, lastChild는 price가 된다.

- title 노드 입장에서 parentNode는 book 노드가 된다.

- book 노드 입장에서 parentNode는 books 노드가 된다.

- books 노드의 입장에서 firstChild 노드는 좌측의 book 노드이며, lastChild 노드는 우측의 book 노드가 된다.

- previousSibling 프로퍼티와 nextSibling 프로퍼티는 자식노드들 사이의 관계를 나타낸다. 예를 들어

author 노드의 입장에서 previousSibling은 title노드가 되고, nextSibling은 price가 된다.

- book 노드의 childNodes는 title노드, author노드, price노드가 되며, NodeList의 형태로 저장된다.

- NodeList는 childNodes로 구한 자식 노드에 접근할 수 있도록 하기 위해서 아래와 같은 두 가지를 제공하고 있다.



- Node 인터페이스의 주요 프로퍼티

 프로퍼티 타입

프로퍼티 이름 

설명 

String 

nodeName 

노드의 이름 

String  

nodeValue 

노드의 값 

unsigned short 

nodeType 

노드 타입 

Node 

parentNode 

부모노드 

Node

childNodes

자식 노드 목록 

Node 

firstChild 

첫 번째 사식 노드 

Node 

lastChild 

 마지막 자식 노드

Node 

previousSibling 

현재 노드와 같은 부모를 갖는 자식 노드 중 현재 노드 이전의 자식 노드 

 Node

nextSibling 

현재 노드와 같은 부모를 갖는 자식 노드 중 현재 노드 다음의 자식 노드 

 Document

ownerDocument 

이 노드가 포함된 Document 객체



-changeHTMLUsingDOM.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var count=0;
    function addItem(){
        count++;
        
        var newItemE=document.createElement("div");
        newItemE.setAttribute("id","item_"+count);
        
        var html="새로 추가된 아이템["+count+"]&nbsp;";
        html+="<input type=\"button\" value=\"삭제\" onclick=\"removeItem('item_" +count+ "');\"/>";        
    
        //<div id="item_1">
        //새로 추가된 아이템[1]<input type="button" value="삭제"
        //onclick="removeItem('item_1')"/>
        
        newItemE.innerHTML=html;
        
        var itemListDiv=document.getElementById("itemList");
        
        itemListDiv.appendChild(newItemE);
    }
    
    function removeItem(itemId){
        var removeItem=document.getElementById(itemId);
        removeItem.parentNode.removeChild(removeItem);
    }
    
</script>
</head>
<body>
<h1>HTML DOM을 이용한 화면 변경</h1>
<hr/>
<input type="button" value="추가" onclick="addItem(); "/>
<div id="itemList"></div>
 
</body>
</html>
cs



-실행화면



3. XML파일 Javascript로 읽어오기 


-books.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <title>겨울왕국</title>
        <author>디즈니</author>
    </book>
    <book>
        <title>수지의 가수생활</title>
        <author>EBS</author>
    </book>
    <book>
        <title>이솝우화</title>
        <author>미드</author>
    </book>
    <book>
        <title>힐러리의 삶</title>
        <author>클린턴</author>
    </book>
</books>
cs


-getBookXML.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>
<script type="text/javascript">
 
    function getBookList(){
        sendRequest("books.xml"null, displayBookList, "GET");
    }
 
    function displayBookList(){
        if(httpRequest.readyState==4){
            if(httpRequest.status==200){
                //전달받은 XML을 DOM객체에 넣음
                 var Document=httpRequest.responseXML; //Text가 아니라 XML파일을 받았다!
                
                 //DOM 객체에서 Elements추출
                 var booksE=Document.documentElement;
                 
                 //book의 갯수 추출
                 var bookNL=booksE.getElementsByTagName("book");
                 //alert(bookNL.length);
                 
                 //전체데이터 읽고 HTML로 출력
                 var html="";
                 html+="<ol>";
                 for(var i=0;i<bookNL.length;i++){
                     
                     //하나의 book을 읽어냄
                     var bookE=bookNL.item(i);
                     var titleStr=bookE
                         .getElementsByTagName("title")
                         .item(0)
                         .firstChild
                         .nodeValue;
                     
                     var authorStr=bookE
                         .getElementsByTagName("author")
                         .item(0)
                         .firstChild
                         .nodeValue;
                     
                     html+= "<li>"
                         + titleStr
                         +"&nbsp;-&nbsp;"
                         + authorStr+"</li>";
                 }
                 html+="</ol>";
                 
                 document.getElementById("bookDiv").innerHTML=html;
            
            }
        }
    }
     
    window.onload=function(){
        getBookList();
    }
</script>
 
</head>
<body>
<h1 id="list">Book List</h1>
<hr/>
<div id="bookDiv" style="display:block; margin:0 auto;"></div>
 
</body>
</html>
cs


-실행화면




4. newsTtitle 을 XML 파일로 받아오기 

- 저번에는 'httpRequest.responseText'로 받았지만 이번에는 'httpRequest.responseXML'을 이용해서  

XML 파일로 받아보자. (쉼표보다 XML파일로 가져오는게 더 간편하다)


-newsTitleXML.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    div{
        margin:auto;
        border:1px solid #0000ff;
        width:600px;
        height:70%;
        padding:10px;
    }
    
</style>
<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>
<script type="text/javascript">
    function newsTitle(){
        sendRequest("newsTitleXML_ok.jsp"null, displayNewsTitle, "GET");
        
        setTimeout("newsTitle()",3000);
    }
    
    function displayNewsTitle(){
        if(httpRequest.readyState==4){
            if(httpRequest.status==200){
                
                var doc=httpRequest.responseXML;
                //alert(doc); //objext XMLDocument
                
                var count=
                    doc.getElementsByTagName("count")
                    .item(0)
                    .firstChild
                    .nodeValue;
                
                //alert(count);
                
                if(count>0){
                    //title의 갯수
                    var titleNL=doc.getElementsByTagName("title");
                    
                    var htmlData="<ol>";
                    
                    for(var i=0;i<titleNL.length;i++){
                        htmlData+="<li>"
                            +titleNL.item(i).firstChild.nodeValue
                            +"</li>";
                    }
                    htmlData+="</ol>";
                    
                    var newsDiv=document.getElementById("news");
                    
                    newsDiv.innerHTML=htmlData;
                }
            }else{
                alert(httpRequest.status+":"+
                        httpRequest.statusText);
            }
            
        }
    }
    
    window.onload=function(){
        newsTitle();
    }
</script>
</head>
<body>
<div id="news"></div>
<input type="text">
</body>
</html>
cs


-newsTitleXML_ok.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%@page import="java.util.Date"%>
<%@ page contentType="text/xml; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<%!
    String[] newsTitle={
            "돈봉투·명품 넥타이 받은 김학의가 '전화해놨다' 했다",
            "'가난해?' 죽고싶게 묻고, 죽지 않을 만큼 준다",
            "경남FC '한국당 막무가내···징계 땐 책임져야'",
            "경찰 '승리 성접대 의혹 사실로 확인'",
            "검 '김성태 딸 부정채용' KT 전 전무 구속 기소",
            "법관들 '침묵' 역이용한 임종헌"
    };
 
%>
 
<result>
    <count><%=newsTitle.length %></count>
    <data>
        <%for(int i=0;i<newsTitle.length;i++){ %>
            <title><%=newsTitle[i]+" | "+new Date() %></title>
        <%%>
    </data>
</result>
cs


-실행화면


: 밑에 inputbox에 텍스트를 입력해놓아도 지워지지 않는것으로 보아 새로고침이 되지않는다.

그리고 위의 텍스트박스를 보면 setTimeout()함수를 통해 3초마다 호출이 되므로 3초마다 시간이 바뀌는 모습을 확인할 수 있다.




5. Javascript에서 클래스 사용 

-자바스크립트에서 클래스를 생성할 수 있다.

자바스크립트에서 클래스를 생성하는 다양한 방식을 예제로 살펴보자.


-member.js : 클래스 생성 역할

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Member 클래스
//얘는 생성자로 초기화해준 것과 같은것
Member =function(id,name,addr){
    this.id=id;
    this.name=name;
    this.addr=addr;
};
 
//클래스 안에 함수 정의(setter)
//얘는 메소드를 만들어서 setter로 초기화
Member.prototype.setValue=function(id,name,addr){
    this.id=id;
    this.name=name;
    this.addr=addr;
};
 
//클래스 안에 함수 정의(getter)
Member.prototype.getValue=function(){
    return "["+this.id+"]"+this.name+"("+this.addr+")";
};
cs

-log.js : console이라는 id를 가진 태그에 출력해주는 기능을 한다.

1
2
3
4
5
6
function log(msg){
    
    var consolE=document.getElementById("console");
    
    consolE.innerHTML+=msg+"<br/>";
}
cs


-memberClass.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=cp%>/data/js/log.js"></script>
<script type="text/javascript" src="<%=cp%>/data/js/member.js"></script>
<script type="text/javascript">
    function memberClass(){
        //1.member.js없이 실행(메모리에 객체생성)
        var object1={};
        object1.id="suzi";
        object1.name="배수지";    
        log("log1: "+object1.id+", "+object1.name);
        
        //2.member.js없이 실행(메모리에 객체생성)
        var object2={};
        object2.id="zhihyo";
        object2.name="송지효";    
        log("log2: "+object2.id+", "+object2.name);
        
        //3.Member 클래스 객체 생성후 변수명으로 호출
        var member=new Member("songhee","천송이","강남");
        log("member1: "+member.id+", "+member.name+", "+member.addr);
        
        //4.setter로 초기화하고 변수로 호출
        member.setValue("hyolee","이효리","제주도");
        log("member2: "+member.id+", "+member.name+", "+member.addr);
        
        //5.getter로 호출
        var memberInfo=member.getValue();
        log("member.getValue(): "+memberInfo);
    }
    
    window.onload=function(){
        memberClass();
    }
</script>
</head>
<body>
<h1>Javascript 클래스 사용</h1>
<hr/>
 
<div id="console"></div>
</body>
</html>
cs


-실행화면



6. Javascript를 이용해 JSON형식으로 데이터받기 

-[], {}, ""를 이용해서 JSON형식에 맞게 데이터를 생성해주고

그 데이터를 자바스크립트에서 가져오는 예제이다.


-jsonUse.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #result{
        border:1px dotted #0000ff;
    }
    
    div{
        margin:auto;
        width:600px;
        height:100%;
    }
</style>
<script type="text/javascript">
    function useJson(){
        var userArray=[
           {
               userId:"suzi",
               name:"배수지",
               age:25,
               phone:[
                     {home:["031-111-1111","032-222-2222"]}, 
                     {office:["02-333-3333","051-444-4444"]}
                     ]
           },//배열0         
           {
               userId:"songhee",
               name:"천송이",
               age:38,
               phone:[{},{}]
           },//배열1     
           {
               userId:"zhihyo",
               name:"송지효",
               age:37,
               phone:[{},{}]
           }//배열2         
        ];
        
        //한개의 데이터 읽기
        var id=userArray[0].userId;//suzi
        var name=userArray[0].name;//배수지
        var age=userArray[0].age;//25
        var homePhone1=userArray[0].phone[0].home[0];//031-111-1111
        var homePhone2=userArray[0].phone[0].home[1];//032-222-2222
        var officePhone1=userArray[0].phone[1].office[0];
        
        var printData=id+", "+name+", "+age+"<br/>";
        printData+="userArray[0].phone[0].home[0]: "+homePhone1+"<br/>";
        printData+="userArray[0].phone[0].home[1]: "+homePhone2+"<br/>";
        printData+="userArray[0].phone[1].home[0]: "+officePhone1+"<br/>";
        
        var resultDiv=document.getElementById("result");
        resultDiv.innerHTML=printData;
        
    }
    
    window.onload=function(){
        useJson();
    }
</script>
</head>
<body>
<h1>JSON(Javascript Object Notation)</h1>
<hr/>
<div id="result"></div>
</body>
</html>
cs



-실행화면





+ Recent posts