본문 바로가기
STUDY/jQuery & Ajax

Json을 사용해서 자바스크립트의 객체 생성

by Anne of Green Galbes 2019. 4. 3.

Json을 사용해서 자바스크립트의 객체 생성


○ 장점

 - 자바스크립트로 패키지까지 작성 가능하다

○ 패키지 생성

방법1 : var com = new Object();

방법2 :var com = { };


◈ 패키지를 중첩해서 정의하고 싶을 때는 각 단계별로 매번 객체를 생성해야한다

com.today = new Object();

com.today.day = function(day){

this.day = day;

}


com.tomorrow = new Object();

com.tomorrow.day = function(day){

this.day = day;

}


◈ 패키지 생성 오류

var com.today = new Object();

var com.tomorrow.day = new Object();

○ 메소드 생성

- prototype : 메소드 생성

- 메소드이름 : function(매개변수){ }

 - 임의의 메소드도 생성 가능하다

com.today.day.prototype = {

setValue:function(day){

this.day = day;

}


toString:function(){

return "toStrung메소드" + this.day;

}

}


예제 1


① member_json.js

//패키지 생성

var com = new Object();

com.util = new Object();

com.util.Member = function(id,name,addr){

this.id = id;

this.name = name;

this.addr = addr;

};


com.util.Member.prototype={

setValue:function(id,name,addr){

this.id = id;

this.name = name;

this.addr = addr;

},

//id의 setter 생성

setId:function(id){

this.id = id;

},

getValue:function(){

return this.id + ":" + this.name + ":" + this.addr;

},

getId:function(){

return this.id;

},

//임의의 메소드도 생성가능

toString:function(){

return "toString 메소드 - " + this.id + ":" + this.name + ":" + this.addr;

}

}


② memberJsonClass.jsp

○ window.onload = function(){

실행할 부분

   }

  - 해당 문서를 시작할 때 실행

<script type="text/javascript" src="<%=cp%>/data/js/log.js"></script>

<script type="text/javascript" src="<%=cp%>/data/js/member_json.js"></script>


<script type="text/javascript">

function memberClass(){

  //① 생성자로 초기화

var member = new com.util.Member("suzi","수지","서울");

log("member1 : " + member.id + ", " + member.name + ", " + member.addr);


//② 메소드로 초기화

member.setValue("vegemil","베지밀","서울");

log("member2 : " + member.id + ", " + member.name + ", " + member.addr);


//③ getter로 값 가져오기

var memberInfo = member.getValue();

log("member.getValue : " + memberInfo);


//④ toString메소드 사용

member.setId("hyolee");

log("member.toString() : " + member.toString());


var id = member.getId();

log("member.getId() : " + id);

}

window.onload = function(){

memberClass();

}


</script>


예제 2 Json 사용


① newsTitleJson.jsp

newsTitle

○ httpRequest.js를 이용하여 Ajax 실행

○ 3초마다 자기자신을 실행


displayNewsTitle

○ eval()

- 내장 함수

- eval( string )

- 변수를 자바스크립트의 함수처럼 사용하도록 해주는 명령어

- 변수를 객체화한다

- eval('2+2') → 4

<script type="text/javascript" src="<%=cp%>/data/js/httpRequest.js"></script>

<script type="text/javascript">


function newsTitle(){

sendRequest("newsTitleJson_ok.jsp", null, displayNewsTitle, "GET");

setTimeout(newsTitle, 3000);

}

function displayNewsTitle(){

if(httpRequest.readyState==4){

if(httpRequest.status==200){

var jsonStr = httpRequest.responseText;

var jsonObject = window.eval('(' + jsonStr + ')');


//여기서 count를 꺼내서 보여준다

//alert(jsonObject.count);


//여기서 count를 찾음

var count = jsonObject.count;

if(count>0){


//for문으로 넘어온 데이터를 분해하여 출력데이터 작성

var htmlData = "<ol>";

for(var i=0;i<count;i++){

var publisherStr = jsonObject.titles[i].publisher;

var headlineStr = jsonObject.titles[i].headline;

htmlData += "<li>" + headlineStr + " [" + publisherStr + "]</li>";

}

htmlData += "</ol>";

var newsDiv = document.getElementById("newsDiv");

newsDiv.innerHTML = htmlData;

}

}

}

}

window.onload = function(){

newsTitle();

};

</script>

</head>


② newsTitleJson_ok.jsp

○ json형식일 때는 plain으로 변경

○ json형식 : { "이름" : 값", "이름2" : "값2", .... }

○ 배열 : [ { "이름" : "값" }, {"이름2" : "값2" }, .... ]

<%@ page contentType="text/plain; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

%>

{

"count":5,

"titles":[

{

"publisher":"조선",

"headline":"예은아빠 '박근혜 감옥 갔으니 됐다'는 말에 힘 빠지더..."

},

{

"publisher":"한국",

"headline":"황교안의 '축구장 유세', 선관위가 허용?"

},

{

"publisher":"한겨레",

"headline":"정관수술했는데 늦둥이가 이 말에 부모님 반응?"

},

{

"publisher":"동아",

"headline":"기승전 갱년기... 나는 열 시간을 울었다"

},

{

"publisher":"중앙",

"headline":"MB의 주옥같은 명언과 '주어는 없다'는 나경원"

}

]

}


○ 다음과 같이 작성 가능

  - 배열로 작성된 내용을 json형식으로 변환

<%@ page contentType="text/plain; charset=UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

request.setCharacterEncoding("UTF-8");

String cp = request.getContextPath();

%>

<%!

String newsTitle[] = {

"예은아빠 '박근혜 감옥 갔으니 됐다'는 말에 힘 빠지더...",

"황교안의 '축구장 유세', 선관위가 허용?",

"정관수술했는데 늦둥이가 이 말에 부모님 반응?",

"기승전 갱년기... 나는 열 시간을 울었다",

"타지키스탄 효녀 '또냐'에게 가족사진을 선물했다",

"'우파 전대협' 반문재인 대자보, 진짜 총학생회의 고민은?",

"MB의 주옥같은 명언과 '주어는 없다'는 나경원"

};

String newsPublisher[] = {"중앙","한국","동아","한겨레","조선","CNN","디스패치"};

%>

{

"count":<%=newsTitle.length%>,

"titles":[

<%

for(int i=0;i<newsTitle.length;i++){

out.print("{");

out.print("headline:\"" + newsTitle[i] + "\"");

out.print(",");

out.print("publisher:\"" + newsPublisher[i] + "\"");

out.print("}");

if(i!=(newsTitle.length-1)){

out.print(",");

}

}

%>

]

}


댓글