[ 목차 ]
1. Ajax
2. Ajax 관련 메서드
* ajax 엄청엄청 중요한 아이임!! 하지만,, 중요한만큼 어려움,,,
1. Ajax
[ 1. Ajax란?]
- Ajax(Asynchronous Javascript and XML)란
자바스크립트를 이용해 비동기 방식으로 자료를 전송 요청하는 것을 가리킨다.
( 1 ) Ajax 사용 전 방식 (동기방식)
- 방문자가 자료를 요청하면 반드시 서버 컴퓨터를 거쳐야만 자료를 요청할 수 있다.
이 방식으로 자료를 요청하면 잠시 페이지가 서버 스크립트 페이지로 갱신되어 화면이 깜빡거리고,
그동안 사용자는 어떤 작업도 할 수 없게 된다.
- 동기방식으로 클라이언트가 서버에 요청하면 서버가 요청을 처리하는 동안 클라이언트는 다른 동작을 할 수가 없다.
( 화면전환o )
( 2 ) Ajax 사용 후 방식 (비동기 방식)
- Ajax를 사용해 방문자가 서버에 자료를 요청했을 경우, 서버 스크립트 페이지를 거치지 않아도 자료를 받아 올 수 있다.
즉 방문자(client)는 서버에 자료를 요청하는 사이에 다른 작업 을 할 수 있다.
블로그의 게시글에 댓글을 달 때 페이지 전환 없이 바로 할 수 있는 것도 Ajax를 사용한 것이다.
- 클라이언트가 서버에 요청하고 서버가 요청을 처리하는 동안에 클라이언트는 다른 일을 할 수 가 있다.
서버의 동작과 관계없이 클라이언트는 동작을 할 수 있다. ( 화면전환x )
ex) 특정한 부분만 화면을 업데이트 시키는 것
( 댓글 등록하면 나머지는 그대로이고 댓글부분만 업데이트 되어서 화면이 바뀐다. )
[ 2. 웹 서버 설치하기 ]
- Apache Tomcat을 설치한다.
* Apache HTTPS <-- Web Server (정적 페이지만 지원) : html, css, js
* B < -- > Web1 Server < -- > WAS < -- > DB
Web2
Web3
. . . .
Webn
* Apache Tomcat <-- Web Application Server (정적과 동적 페이지를 지원) : html, css, js, java, jsp, ..
* B < -- > WAS < - -> DB
[ 3. 웹 호스팅 등록하여 서버 이용하기 ]
- 닷홈 (www.dothome.co.kr) 웹호스팅을 등록한다.
2. Ajax 관련 메서드
[ 1. Ajax 관련 메서드들 ]
(1) load() 메서드
- 사용자가 지정한 URL 주소에 데이터를 전송하고 외부 콘텐츠를 요청하여 가져올 때 사용한다.
요청한 콘텐츠를 이용해 선택한 요소에 내용을 바꿀 수 있다.
// 기본형
$(요소 선택).load(url, data, 콜백 함수)
/* document_1.txt 코드 */
<h1>삽입 제목</h1>
<p>삽입 내용</p>
/* jquery_ajax_1_test.html 코드 */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title> Ajax </title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function () {
$("#d1").load("document_1.txt");
});
//]]>
</script>
</head>
<body>
<div id="d1">내용</div>
</body>
</html>
<!--ctrl + alt + L : 코드 줄 정리-->
(2) $.ajax() 메서드
- 다음은 $.ajax() 메서드의 기본형이다.
// $.ajax() 메서드의 기본형
$.ajax ({
url: "전송 페이지"(액션 페이지),
type: "전송 방식"(get, post 방식),
data: "전송할 데이터",
dataType: "요청한 데이터 타입"("html", "xml", "json", "text", "jsonp"),
success: function(result) {
전송 성공하면 실행할 실행문들;
}
});
/* welcome.jsp 코드 */
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!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>
</head>
<body>
환영합니다. ${param.username}님
</body>
</html>
/* jquery_ajax_2_test.html 코드 */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title> Ajax </title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function () {
// 자바스크립으로 표현한 코드
$("member").on("submit", function () {
var d = $(this).serialize();
// 폼 요소를 serialize 한다. 즉, 데이터를 일렬로 나열한다.
// ex) username=honggildong&passwd=hong
alert(d); // "username=honggildong&passwd=hong" 출력
});
});
//]]>
</script>
</head>
<body>
<form action="member.jsp" method="post" name="member" id="member">
<fieldset>
<legend>회원가입</legend>
<p>
<label for="username">이름</label> <input type="text" name="username"
id="username"/>
</p>
<p>
<label for="passwd">비밀번호</label> <input type="password"
name="passwd" id="passwd"/>
</p>
<p>
<input type="submit" value="확인"/>
</p>
</fieldset>
</form>
<h1 id="txt1"></h1>
</body>
</html>
/* jquery_ajax_2_test.html 코드 */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title> Ajax </title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function () {
// 자바스크립으로 표현한 코드
$("member").on("submit", function () {
var d = $(this).serialize();
// 폼 요소를 serialize 한다. 즉, 데이터를 일렬로 나열한다.
// ex) username=honggildong&passwd=hong
alert(d); // "username=honggildong&passwd=hong" 출력
$.ajax({
url: "welcome.jsp", // 데이터를 전송할 URL 주소
type: "post", // 데이터 전송하는 방식
data: d, // 데이터 전송할 값
success: function (result) {
$("#txt1").html(result);
// 받은 값이 result 변수에 들어가고 그 값을
// id=txt1 요쇼인 구간에 그 값을 넣어라.
}
});
return false;
// form action 페이지로 이동하는 것을 차단한다.
});
});
//]]>
</script>
</head>
<body>
<form action="member.jsp" method="post" name="member" id="member">
<fieldset>
<legend>회원가입</legend>
<p>
<label for="username">이름</label> <input type="text" name="username"
id="username"/>
</p>
<p>
<label for="passwd">비밀번호</label> <input type="password"
name="passwd" id="passwd"/>
</p>
<p>
<input type="submit" value="확인"/>
</p>
</fieldset>
</form>
<h1 id="txt1"></h1>
</body>
</html>
(3) $.post() 메서드
/* example09_08.html 코드 */
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>$.ajax로 jsp 파일 로드하기</title>
<style>
td {
border: 1px solid gray;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.js"
type="text/javascript"></script>
<script type="text/javascript">
/*
- $.post() 함수는 post방식으로 서버와 통신하는 jQuery 함수이다.
- $.post() 함수는 서버의 welcome.jsp 페이지를 post방식으로 요청한다.
*/
/* jquery_ajax_2_test.html 코드 실행결과와 같은 실행결과를 가진다. */
$(function () {
$("#member").on("submit", function () {//"확인"버튼을 눌렀을 때..
var username = $("#username").val(); // 서버로 보낼 데이터를 입력창에서 얻어온다.
var passwd = $("#passwd").val();
var sendData = 'username=' + username + '&passwd=' + passwd;
alert(sendData);
// $.ajax 코드를 간소화 시킨 코드가 바로 아래의 코드가 된다.
$.post( // 문자열 형식의 데이터를 welcome.jsp 파일로 보낸다.
"welcome.jsp", sendData, function (msg) {
// 첫번째 매개변수: url 주소, 두번째 매개변수: 보내는데이터, 세번째 매개변수: 실행할 코드
$('#txt1').html(msg);
});
return false;
});
});
</script>
</head>
<body>
<form action="member.jsp" method="post" name="member" id="member">
<fieldset>
<legend>회원가입</legend>
<p>
<label for="username">이름</label> <input type="text" name="username"
id="username"/>
</p>
<p>
<label for="passwd">비밀번호</label> <input type="password"
name="passwd" id="passwd"/>
</p>
<p>
<input type="submit" value="확인"/>
</p>
</fieldset>
</form>
<h1 id="txt1"></h1>
</body>
</html>
(4) $.get() 메서드
/* item.xml 코드 */
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item id="1" name="레몬">
<price>3000</price>
<description> 레몬에 포함되어 있는 쿠엔산은 피로회복에 좋다. 비타민C도 풍부하다. </description>
</item>
<item id="2" name="키위">
<price>2000</price>
<description> 비타민C가 매우 풍부하다. 다이에트와 미용에도 매우 좋다. </description>
</item>
<item id="3" name="블루베리">
<price>5000</price>
<description> 블루베리에 포함된 anthocyanin(안토시아닌)은 눈피로에 효과가 있다. </description>
</item>
<item id="4" name="체리">
<price>5000</price>
<description> 체리는 맛이 단 성분이 많고 피로회복에 잘 듣는다. </description>
</item>
<item id="5" name="메론">
<price>5000</price>
<description> 메론에는 비타민A와 칼륨이 많이 포함되어 있다. </description>
</item>
<item id="6" name="수박">
<price>15000</price>
<description> 수분이 풍부한 과일이다.</description>
</item>
</items>
/* example09_07.html 코드 */
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XML 파일을 GET 방식으로 로드하기</title>
<style>
td {
border: 1px solid gray;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript">
/*
- $.get() 함수를 이용해서 item.xml 파일을 불러온다.
- $.get() 함수의 첫번째 매개변수에는 서버의 URL 주소를 지정한다.
- $.get() 함수의 두번째 매개변수인 콜백함수를 이용해서 서버에서 보내온 XML 형식의 데이터를 data 로 받늗다.
*/
$(function () {
$.get('item.xml', function (data) { // 내가(클라이언트) 서버에 get이라는 메서드로 요청해서 item.xml을 가지고 테이블을 만들어서 내 화면(클라이언트)에 보여주게 되는 것이다.
//alert(data);
$("#treeData").append(
"<tr><td>id</td>" + "<td>name</td>" + "<td>price</td>"
+ "<td>description</td>" + "</tr>");
$(data).find('item').each(function () { // 서버에서 얻어온 데이터에서 셀렉터로 item태그를 찾는다.
var $item = $(this); // 6개의 item태그중 현재 처리중인 item태그를 this로 접근한후에 이를
$("#treeData").append("<tr>" + "<td>" // this로 접근한 후에 이를 $(this)를 사용하여 jQuery객체를
+ $item.attr("id") + "</td>" + "<td>" //생성함
+ $item.attr("name") + "</td>" + "<td align='right'>"
+ $item.find("price").text() + "</td>" + "<td>"
+ $item.find("description").text() + "</td>" + "</tr>");
});
});
});
</script>
</head>
<body>
<table id="treeData"></table>
</body>
</html>
* localhost 에 192.168.30.199 를 적고 그 주소로 들어가게 되면 강사님의 웹서버로 들어가게 된다.
바로 위의 사진이 로컬코드로 서버쪽(강사님 pc쪽)에 있는 items.xml 을 요청해서 내 pc에 띄워진 것이다.
내 pc는 클라이언트가 되고 강사님 pc는 서버가 된 것이다. 요청하는 방법은 get( ) 메서드가 되었다.
[ 데이터 표현 방법 ]
- 1) CSV(comma separate value) : 컴마를 구분자로 데이터를 표현하는 방법
학번,이름,주소,전화번호
1,홍길동,서울,02-333-444 <-- 이것 자체로만 보면 1이 무엇을 나타내는 데이터인지,
서울이 무엇을 의미하는 데이터인지 알기 어렵다
2,유재성,경기,010-33-444
- 2) XML (1TB = 1GB(순수데이터) + 999GB(데코하는 태그))
: 데이터를 태그로 표현하는 방법(데이터를 명확하게 구별하는 방법)
<xml>
<list>
<student>
<학번>1</학번>
<이름>홍길동</이름>
<주소>서울</주소>
. . . . .
</student>
<student>
<학번>2</학번>
<이름>유재석</이름>
<주소>경기</주소>
. . . . .
</student>
</list>
- 3) JSON : XML의 코드를 간결화 한 데이터 방법
[
{ 학번: 1, 이름: 홍길동, 주소: 서울},
{ 학번: 2, 이름: 유재석, 주소: 경기},
]
(5) $.getJSON() 메서드
* 요청하는 방법이 get( ) 메서드가 되고 데이터 리턴 반환되는 타입은 JSON 형식으로 받게 되는 것이다.
[ 2. XML 데이터 요청하기 ]
- XML ( Extensible Markup Language: 확장성 마크업 언어 ) : 확장 가능한 언어
- 태그명을 사용자가 임의로 작성할 수 있고 주로 데이터를 배포하는 목적으로 사용된다.
/* jquery_ajax_3_test.html 코드 */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title> Ajax </title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function() {
$.ajax({ // 외부에 데이터 전송 또는 요청한다.
url: "rank.xml", // 데이터를 요청할 URL 주소
//data: ... <-- 전송할 데이터 값
dataType: "xml", // 요청할 데이터의 타입
success: function(result) {
if ($(result).find("rank").length > 0) {
$(result).find("rank").each(function(){
var name = $(this).find("k").text(); // 맨처음 name 변수에 '김연아'가 들어간다. 그 다음 순서로는 '이상화', 그 다음으로는 '모태범' 이 name 변수에 들어간다.
var result = "<li>" + name + "</li>";
$("#wrap ol").append(result);
// id = wrap요소인 ol 태그에 result 값들을 붙여라.
});
}
}
});
});
//]]>
</script>
</head>
<body>
<h1>인기 검색어</h1>
<div id="wrap">
<ol></ol>
</div>
</body>
</html>
/* rank.xml 코드 */
<?xml version="1.0" encoding="UTF-8"?>
<result>
<item>
<rank>
<k>김연아</k>
</rank>
<rank>
<k>이상화</k>
</rank>
<rank>
<k>모태범</k>
</rank>
</item>
</result>
[ 3. JSON 데이터 요청하기 ]
- JSON ( JavaScript Object Notation 약자 ) : 자바스크립트 객체 표기법
- JSON으로 데이터를 표기할 때는 중괄호 내에 key와 value 값을 쌍으로 표기한다.
// 기본형
{key:value1, key2:value2, key3:value3, ... }
/* jquery_ajax_4_test.hmtl 코드 */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Ajax</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function() {
$.ajax({
url: "rank.json",
dataType: "json",
success: function(result){
$.each(result.rank, function(i,d){
$("#wrap ol").append("<li>" + d["k"] + "</li>"); // d 는 {"k":"김연아"}를 의미한다. d["k"] 는 {"k":"김연아"} 에서 "k"인 값 "김연아"를 의미한다.
});
}
});
});
//]]>
</script>
</head>
<body>
<h1>인기 검색어</h1>
<div id="wrap">
<ol></ol>
</div>
</body>
</html>
/* rank.json 코드 */
{"rank":[
{"k":"김연아"},
{"k":"이상화"},
{"k":"모태범"}]
}
[ 실습 : Ajax로 RSS 연동하기 ]
- RSS (Really Simple Syndication) : 사전적으로 '초간편 배급(배포)' 라는 의미이다.
* 내 서버에서 조선일보한테 요청하는 코드이다..?
/* jquery_ajax_rss.html 코드 */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<title> RSS 연동하기 </title>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function () {
//변수 g에 크로스 도메인의 데이터를 가져올 수 있도록 구글 주소를 저장하였습니다.
var g = "https://api.rss2json.com/v1/api.json?rss_url=";
$("news_wrap h2 a").on("click", function (e) {
e.preventDefault(); <!-- <a> 태그에 링크를 차단함 -->
$("news_wrap h2 a").removeClass("on"); <!-- <a>에 "on" class를 삭제한다. -->
$(this).addClass("on"); <!-- 클릭한 <a>에 class="on"을 생성한다. -->
$.ajax({
url: g + $(this).attr("href"),
dataType: "json",
success: function (data) {
let obj = JSON.stringify(data);
alert(obj);
$("#news_list").empty(); <!-- <ul>에 하위 요소를 모두 제거한다. -->
$.each(data.items, function (i, d) {
if (i == 5)
return false;
let title = d["title"]; <!-- title 키의 값을 가져온다. -->
let date = new Date(d["pubDate"]); <!-- 뉴스 작성 날짜 객체 생성 -->
let m = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
let lk = d["link"]; <!-- 앞서 구해온 데이터를 이용해 정보 목록 태그를 생성한다. -->
$("#news_list").append('<li><a href="' + lk + '" target="_blank">' +
title + '</a> <span>' + m + '</span></li>');
});
}
});
});
$("#news_wrap h2 a").eq(0).click();
});
</script>
<style type="text/css">
/*기본 세팅*/
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
body {
font: 12px Margun Gothic, "맑은고딕", gulim, "굴림", sans-serif;
color: #333;
padding-top: 20px;
}
h1, h2, h3, h4, h5, h6 {
font-size: 100%;
font-weight: normal;
}
a {
color: #333;
text-decoration: none;
outline: none;
}
h1 {
font-size: 2em;
text-align: center;
margin-bottom: 10px;
color: #c00;
}
/*탭 메뉴 디자인*/
#news_wrap {
width: 380px;
margin: 0 auto;
background: #FFF url("images/rss_bg.gif") 0 0 repeat-x;
}
#news_wrap li {
height: 25px;
line-height: 25px;
position: relative;
}
#news_wrap span {
position: absolute;
top: 0;
right: 3px;
}
#news_wrap li a {
display: block;
width: 210px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding-left: 15px;
background: url("images/bullet.gif") 5px 10px no-repeat;
}
#news_wrap h2 {
float: left;
padding-right: 3px;
margin-bottom: 10px;
}
#news_list {
clear: both;
}
/*비활성화 탭 버튼 모양*/
#news_wrap h2 a {
display: inline-block;
padding: 8px 10px;
border: 1px solid #aaa;
border-bottom: none;
border-radius: 5px 5px 0 0;
background: #ccc;
}
/*비활성화 탭 버튼 모양*/
#news_wrap h2 a.on {
background-color: #fff;
font-weight: bold;
}
</style>
</head>
<body>
<h1>조선닷컴</h1>
<div id="news_wrap">
<h2> <!-- 초기에 첫 번째 버튼에만 class="on"이 포함되어 있습니다. -->
<a href="https://www.chosun.com/arc/outboundfeeds/rss/?outputType=xml" class="on">
오늘의 주요뉴스</a>
</h2>
<h2>
<a href="https://www.chosun.com/arc/outboundfeeds/rss/category/entertainments/?outputType=xml">엔터테이먼트</a>
</h2>
<h2>
<a href="https://www.chosun.com/arc/outboundfeeds/rss/category/sports/?outputType=xml">스포츠</a>
</h2>
<ul id="news_list">
</ul>
</div>
</body>
</html>
* XML에서 특수 문자를 사용하는 방법
: 안드로이드 UI를 디자인하다 보면 한번쯤은 &, <, > 와 같은 기호들을 사용할 때가 있다.
하지만 이러한 특수 기호를 사용하면 다음과 같은 메시지가 출력된다.
'Language > JavaScript' 카테고리의 다른 글
07_제이쿼리 이벤트 (0) | 2023.01.12 |
---|---|
06_제이쿼리 문서 객체 선택자와 조작법 (0) | 2023.01.12 |
05장(2)_ 문서 객체 모델(DOM) (0) | 2023.01.11 |
05장(1)_ 문서 객체 모델(DOM) (0) | 2023.01.11 |
04장_자바스크립트와 객체 (0) | 2023.01.10 |