본문 바로가기
STUDY/jQuery & Ajax

자바스크립트로 Ajax 구현

by Anne of Green Galbes 2019. 4. 1.

자바스크립트로 Ajax 구현

○ 자바스크립트에서는 Ajax를 바로 구현하지 못해 XMLHttpRequest객체를 생성해야 한다

- XMLHttpRequest = createXMLHttpRequest();

var xmlHttp;

function createXMLHttpRequest(){


if(window.XMLHttpRequest){

xmlHttp = new XMLHttpRequest(); //non IE

} else if(window.ActiveXObject){

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") //IE 5.0이후

} catch (e) {

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE 5.0이전

}

}

return xmlHttp;


}


예제 1

① helloAjax.jsp

ajaxRequest

○ open() 메소드 : open(㉠,㉡,㉢)

- XMLHttpRequest.open("GET","helloAjax_ok.jsp",true);

- ㉠ : HTTP 요구 방식

GET, POST, HEAD 중 하나이거나 서버에서 지원하는 다른 방식

모두 대문자로 표기해야 한다

- ㉡ : 요구하고자 하는 URL

- ㉢ : true : 비동기방식

false : 동기방식

생략가능 - 기본 값은 true

○ send()메소드

- XMLHttpRequest.send(null);

- post방식의 경우 뒤에 데이터를 작성

- post방식의 경우 다음 작성

XMLHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");


viewMessage

○ responseText : 서버의 응답을 텍스트 문자열로 반환

○ responseXML : 서버의 응답을 XML객체로 변환

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

<script type="text/javascript">

var XMLHttpRequest;

function ajaxRequest(){

XMLHttpRequest = createXMLHttpRequest();

XMLHttpRequest.open("GET","helloAjax_ok.jsp",true);

//callback이 정석이지만, 이름은 사용자 정의

XMLHttpRequest.onreadystatechange = viewMessage;

XMLHttpRequest.send(null);

}

function viewMessage(){

var responseText = XMLHttpRequest.responseText;

//printDIV의 객체 생성

var divE = document.getElementById("printDIV");

divE.innerHTML = responseText;

}

</script>


② helloAjax_ok.jsp

○ for문 : 지연되는 시간을 보여주기 위해 작성한 것

작성하지 않아도 괜찮음

<%@ 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();

for(int i=0;i<300;i++){

System.out.print("delay...");

}

%>

오늘은 월요일 어려운 Ajax!!


예제 2 Get방식과 Post방식 데이터 전송

① ajaxGetPost.jsp

ajaxRequestGet

○ Get방식으로 데이터를 전송 : 한글은 깨진다

 ○ open메소드에서 url부분에 값을 넣어서 전송


ajaxRequestPost

open메소드에서 값을 넣어서 정송 불가

→ send에서 데이터를 넘긴다 ( XMLHttpRequest.send("greeting="+data); )

 ○ send메소드를 호출하기 전에 아래와 같은 형태로 send()로 보낼 쿼리를 이용해야 한다

- XMLHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");


viewMessage

readyState

- 1 : 요청페이지 정보 설정

- 2 : 요청을 보내기 시작

- 3 : 서버에서 응답오기 시작

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

<script type="text/javascript">

//GET방식

function ajaxRequestGet(){

XMLHttpRequest = createXMLHttpRequest();

var data = document.myForm.greeting.value;

if(data==""){

alert("데이터를 입력해주세요");

document.myForm.greeting.focus();

return;

}

XMLHttpRequest.open("GET","ajaxGetPost_ok.jsp?greeting="+data,true);

XMLHttpRequest.onreadystatechange = viewMessage;

XMLHttpRequest.send(null);

}

//POST방식

function ajaxRequestPost(){

XMLHttpRequest = createXMLHttpRequest();

var data = document.myForm.greeting.value;

if(data==""){

alert("데이터를 입력해주세요");

document.myForm.greeting.focus();

return;

}

XMLHttpRequest.open("POST","ajaxGetPost_ok.jsp",true);

XMLHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");

XMLHttpRequest.onreadystatechange = viewMessage;

XMLHttpRequest.send("greeting="+data);

}

function viewMessage() {

var divE = document.getElementById("printDIV");

if(XMLHttpRequest.readyState==1 || XMLHttpRequest.readyState==2 || XMLHttpRequest.readyState==3){

divE.innerHTML = "<image src='../image/processing.gif' width='50' height='50'>";

} else if (XMLHttpRequest.readyState==4) {

divE.innerHTML = XMLHttpRequest.responseText;

} else{

divE.innerHTML = "<font color='red'>" + XMLHttpRequest.ststus + "에러 발생" + "</font>";

}

}

</script>


② ajaxGetPost_ok.jsp

<%@ 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 protocol = request.getProtocol();

System.out.print(protocol);

//클라이언트 캐쉬 제거

response.setHeader("Pragma", "no-cache");

response.setHeader("Cache-control", "no-store"); //HTTP 1.0버전

response.setHeader("Cache-control", "no-cache"); //HTTP 1.1버전

/*

//이렇게도 가능

if(request.getProtocol().equals("HTTP/1.1")){

response.setHeader("Cache-control", "no-cache"); //HTTP 1.1버전

}

*/

//세션 삭제 후(로그아웃) 뒤로가기 방지

response.setDateHeader("Expires", 0);

%>

<%

String greeting = request.getParameter("greeting");

for(int i=0;i<10000;i++){

System.out.print("기다려...처리중이야");

}

%>

<%="Server : " + greeting %>


예제 3 클라이언트 시간과 서버의 시간을 확인

clock.jsp

printClientTime

new Date() : 현재시간

setTimeout(callback, delay)

 - callback : 호출할 함수

   - delay : 몇 초 마다 실행 1000=1초


requestTime

○ dummy

- 형식만 갖춰서 데이터를 넘길 때 사용

   - 넘겨줄 값은 없지만, 값을 넘겨 실행이 되기 때문에 필요없는 데이터 dummy를 보냄

- 서버가 받아서 사용하지는 않는다

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

<script type="text/javascript">

var XMLHttpRequest;

function printClientTime(){

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

var now = new Date();

var timeStr = now.getFullYear() + "년 " + (now.getMonth()+1) + "월 " + now.getDate() + "일 "

+ now.getHours() + "시 " + now.getMinutes() + "분 " + now.getSeconds() + "초 ";

clientTimeSpan.innerHTML = timeStr;

// 1초마다 자기 자신을 실행

setTimeout(printClientTime, 1000);

}

function requestTime(){

XMLHttpRequest = createXMLHttpRequest();

XMLHttpRequest.open("GET","clock_ok.jsp?dummy=" + new Date().getDate(),true);

XMLHttpRequest.onreadystatechange = printServerTime;

XMLHttpRequest.send(null);

setTimeout(requestTime, 1000);

}

function printServerTime(){

if(XMLHttpRequest.readyState==4){

if(XMLHttpRequest.status==200){

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

serverTimeSpan.innerHTML = XMLHttpRequest.responseText;

}else{

//200이 아닌 경우

}

}else{

//4가 아닌 경우

}

}

window.onload = function(){

printClientTime(); //client 시간

requestTime(); //server 시간

}

</script>

</head>


<body>

<!-- 클라이언트의 시간과 서버의 시간 확인 -->

<h1>Clock</h1>

<br/><br/>

<hr/>

1.현재 클라이언트 시간은 <span id="clientTimeSpan"></span>입니다. <br/>

2.현재 서버 시간은 <span id="serverTimeSpan"></span>입니다.

</body>


clock_ok.jsp

○ 서버 시간 확인시에만 사용

○ 클라이언트에서 넘어오는 데이터를 받을 필요가 없다

○ 서버의 시간만 있으면 된다

<%@page import="java.util.Date" %>

<%@ 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();

//클라이언트 캐쉬 제거

response.setHeader("Pragma", "no-cache");

response.setHeader("Cache-control", "no-store"); //HTTP 1.0버전

response.setHeader("Cache-control", "no-cache"); //HTTP 1.1버전

//세션 삭제 후(로그아웃) 뒤로가기 방지

response.setDateHeader("Expires", 0);

%>

<%=new Date()%>


예제 4 뉴스 타이틀 만들기

○ 다음 부분을 함수로 만들어 값만 주면 자동으로 들어가도록 실행

XMLHttpRequest.open("GET","clock_ok.jsp?dummy=" + new Date().getDate(),true);

XMLHttpRequest.onreadystatechange = printServerTime;

XMLHttpRequest.send(null);


① httpRequest.js

getXMLHttpRequest

XMLHttpRequest객체를 생성


sendRequest

○ Ajax 요청 처리 및 작업하는 부분

function getXMLHttpRequest(){

if(window.ActiveXObject){

try{

return new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

return new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {

return null;

}

}

} else if (window.XMLHttpRequest) {

return new XMLHttpRequest;

} else {

return null;

}

}


//Ajax 요청 및 처리 작업

var httpRequest = null;

function sendRequest(url,params,callback,method){

httpRequest = getXMLHttpRequest();

//method 처리

//method값이 있으면 넘어온 method값을 사용. 없으면 GET으로 설정

var httpMethod = method?method:"GET";

if(httpMethod!="GET" && httpMethod!="POST"){

httpMethod = "GET";

}

//params 처리

var httpParams = (params==null || params=="")?null:params;

//url처리

var httpUrl = url;

if(httpMethod="GET" && httpParams!=null){

httpUrl += "?" + httpParams;

}

httpRequest.open(httpMethod,httpUrl,true);

//POST방식일 경우를 대비해서 작성

httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");

httpRequest.onreadystatechange = callback;

httpRequest.send(httpMethod=="POST"?httpParams:null);

}


② newsTitleCSV.jsp

CSV

- ,(콤마)로 구분된 데이터를 가지고 오겠다

- 이 데이터는 실제로 존재하는 데이터가 아니라, DB에서 가져온 데이터를 콤마로 구분하는 것

<%@ 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">

.news {

font-size: 10pt;

display: block;

margin: 0 auto;

background: yellow;

color: blue;

border: 1px dashed black;

width: 50%;

}

.newsError {

font-size: 10pt;

display: block;

margin: 0 auto;

background: red;

color: red;

border: 1px dashed black;

width: 50%;

}

</style>

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

<script type="text/javascript">

function newsTitle(){

hideNewsDiv();

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

}

function displayNewsTitle(){

if(httpRequest.readyState==4){

if(httpRequest.status==200){

var csvStr = httpRequest.responseText;


//배열이 두개로 분리 : [0] 전체데이터 갯수, [1] 나머지

var csvArray = csvStr.split("|");

var countStr = csvArray[1];

if(countStr==0){

alert("News가 없습니다.");

return;

}

var csvData = csvArray[1];

var newsTitleArray = csvData.split("*");

var html = "";

html += "<ol>";

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

var newsTitle = newsTitleArray[i];

html += "<li>" + newsTitle + "</li>";

}

html += "</ol>";

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

newsDiv.innerHTML = html;

}else{

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

newsDiv.innerHTML = httpRequest.status + ":에러발생";

//IE인 경우

newsDiv.className = "newsError";

//IE가 아닌 경우

newsDiv.setAttribute("class","newsError");

}

}

}

//뉴스보이게

function showNewsDiv(){

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

newsDiv.style.display = "block";

}

//뉴스 숨기기

function hideNewsDiv(){

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

newsDiv.style.display = "none";

}

window.onload = function() {

newsTitle();

}

</script>

</head>


<body>

<h2>헤드라인 뉴스</h2>

<hr/>

<br/>

<div onmouseover="showNewsDiv();" onmouseout="hideNewsDiv();"

style="display: block; border: 3px solid; width: 50%; margin: 0 auto;">

뉴스보기

</div>

<div id="newsDIV" class="news"></div>

<hr/>

</body>


③ newsTitleCSV_ok.jsp

<%@page import="java.util.Date"%>

<%@ 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();

%>

<!-- !의 의미 : 전역변수로 만든다. service 바깥에 생성될 수 있음 -->

<%!

String newsTitle[] = {

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

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

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

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

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

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

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

};

%>

<!-- 위에서 만든 데이터를 보내는 작업 -->

<%

// *은 다음 기사와의 구분표시

// 데이터의 갯수|문장[날짜 시간]*

// 7|예은아빠 '박근혜 감옥 갔으니 됐다'는 말에 힘 빠지더...[2019.4.1 오후 4:14:10]*

// 황교안의 '축구장 유세', 선관위가 허용?[2019.4.1 오후 4:14:10]*

// .....

out.print(newsTitle.length + "|"); //뉴스의 갯수

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

out.print(newsTitle[i] + "[" + new Date() + "]");

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

out.print("*");

}

}

%>


예제 5 자동검색어

① suggestClient.jsp

sendKeyword

○ 키보드를 누를 때마다 실행

sendRequest("suggestClient_ok.jsp", params, displaySuggest, "POST");

- 데이터를 보내는 곳 : suggestClient_ok.jsp

- 보내는 데이터 : params

- 데이터를 받고 실행할 메소드 : displaySuggest

- 보내는 방식 : POST


displaySuggest

○ 받은 데이터 형식 지정

<a href="javascript:select('keyword');">keyword</a><br/>


select

○ 사용자가 제시어에서 클릭한 키워드

<style type="text/css">

.suggest {

display: none;

position: absolute;

left: 11px;

top: 131px;

}

a {

text-decoration: none;

color: black;

}

</style>


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

<script type="text/javascript">

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){

var resultText = httpRequest.responseText;

var resultArray = resultText.split("|");

var count = parseInt(resultArray[0]);

var keywordList = null;

if(count>0){

keywordList = resultArray[1].split(",");

var html = "";

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

//select 호출

html += "<a href=\"javascript:select('" + keywordList[i] + "');\">"

+ keywordList[i] + "</a><br/>";

}

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

suggestListDiv.innerHTML = html;

show();

}

} 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>


② suggestClient_ok.jsp

○ !를 붙이는 이유 : 함수를 사용하기 위해

<%@page import="java.util.Iterator"%>

<%@page import="java.util.ArrayList"%>

<%@page import="java.util.Collection"%>

<%@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();

%>

<%!

//이 데이터는 원래 DB에서 읽어온다

String keywords[] = {"ajax","Ajax","Ajax 실전 프로그래밍","AZA","AZERA",

"자수","자전거","자바 프로그래밍","자바 서버 페이지",

"자바캔","ABC마트","APPLE"};

public List<String> search(String userKeyword){

if(userKeyword==null || userKeyword.equals("")){

return null;

//return Collection.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(",");

}

}

%>


'STUDY > jQuery & Ajax' 카테고리의 다른 글

자바스크립트 객체 : JSON 표기법  (0) 2019.04.02
Document Object Model과 XML  (0) 2019.04.02
Ajax 간단한 예제  (0) 2019.03.31
jQuery  (0) 2019.03.29
Ajax  (0) 2019.03.29

댓글