카테고리 없음

AJAX 기초 정리

surimi🍥 2021. 1. 11. 16:16
반응형

페이지 동작이 필요할 때,

페이지 전체를 리로딩하기 대신, 필요한 정보만 받아 그 부분만 바꾸는 기능

예: 검색바 자동완성, 추천 검색어 등

 

 

<!DOCTYPE html>
<html>
  <body>
    <article></article>
    <input
      type="button"
      value="fetch"
      onclick="
      fetch('css').then(function(response){ // 같은 디렉토리 안의 'css'파일을 읽어온다.
        response.text().then(function(text){
          //alert(text);
          document.querySelector('article').innerHTML = text;
        })
      })
      "
    />
  </body>
</html>

fetch('url');

해당 url을 서버에 요청해 읽어오는 메소드.

.then()

서버가 응답할 때 까지 대기하다가

응답이 끝나면 파라미터 안의 함수를 실행시킨다.

 

function callbackme(){
  consol.log('response end');
}

fetch('html').then(callbackme);

 

만약 없는 파일을 서버에 요청 할 경우, 404에러가 뜨는데

 

콘솔 네트워크 탭

 

콘솔창을 통해 이렇게 디테일을 볼 수 있는데,

이 속성들을 JS 상에 불러와 비교를 할 수 있다.

 

Fragment

Hash

Fragment Identifier

     

Hash를 이용해 서버에 데이터 요청하기

 

list 파일
css, html, javascript 파일

index.html

<!doctype html>
<html>
<head>
<title>WEB1 - Welcome</title>
<meta charset="utf-8">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="colors.js"></script>
<script type="text/javascript">

	// 주소창의 hash를 읽어와 메소드 호출
	if (location.hash) {

		fetchPage(location.hash.substr(1));
	} else {

	}
	
	// 해당 파일 데이터 서버에 요청
	function fetchPage(parameter) {

		fetch(parameter).then(function(response) {
			response.text().then(function(text) {
				document.querySelector('article').innerHTML = text;
			})
		})
	}
	
	// 리스트 출력
	tags = '';
	
	fetch('list').then(function(response) {
	response.text().then(function(text) {
		var items = text.split(','); // ,로 문자열을 나눔
		var i = 0;
		while (i < items.length){
			var item = items[i].trim();
			var tag = '<li><a href="#'+item+'" onclick="fetchPage(\''+item+'\')">' + item + '</a></li>';
			tags = tag + tags;
			i = i + 1;
		}
		
	document.querySelector('#nav').innerHTML = tags; })})
	
</script>
</head>
<body>
	<h1>
		<a href="index.html">WEB</a>
	</h1>
	<input id="night_day" type="button" value="night"
		onclick="
    nightDayHandler(this);
  " />
	<ol id="nav">
		// list가 출력되는 위치
	</ol>

	<article>welcome!</article>

	<h2>WEB</h2>
	<p>The World Wide Web (abbreviated WWW or the Web) is an
		information space where documents and other web resources are
		identified by Uniform Resource Locators (URLs), interlinked by
		hypertext links, and can be accessed via the Internet.[1] English
		scientist Tim Berners-Lee invented the World Wide Web in 1989. He
		wrote the first web browser computer program in 1990 while employed at
		CERN in Switzerland.[2][3] The Web browser was released outside of
		CERN in 1991, first to other research institutions starting in January
		1991 and to the general public on the Internet in August 1991.</p>
</body>
</html>



substring(0, 4) = 문자열 0번부터 3번까지만 출력.

 


XMLHttpRequest 객체 생성하기

var xhttp;
if(window.XMLHttpRequest){
    xhttp = new XMLHttpRequest();
}else{
    // IE5, IE6 일때
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Ajax 서버 요청

서버로 요청할때는 XMLHttpRequest 객체에서 제공하는 api 인 open(), send() 메소드를 사용한다.

메소드설명

open(method, url, async) 요청 타입을 정한다.
method: 요청 타입: GET 또는 POST
url: 서버 (파일) 위치
async: true (비동기식) 또는 false (동기식)
send() 서버로 요청을 보낸다 (GET방식에서 사용)
send(string) 서버로 요청을 보낸다 (POST방식에서 사용)

 

GET Requests

xhttp.open('GET', 'dome_get.asp', true);
xhttp.send();
//위 소스는 이미 캐시댄 결과를 볼 수도 있다. 그런 경우를 피하려면, 유니크 ID를 URL에 삽입해야 한다.

xhttp.open('GET', 'dome_get.asp?t=' + Math.random(), true);
xhttp.send();
//GET 방식으로 요청을 보내고 싶으면, 정보를 URL에 입력해주면 된다.

xhttp.open('GET', 'dome_get2.asp?fname=Henry&lname=Ford', true);
xhttp.send();

POST Requests

xhttp.open('POST', 'demo_post.asp', true);
xhttp.send();

HTML 형식으로 POST 요청을 하려면, setRequestHeader()를 이용하여 HTTP 헤더 정보를 넣어주면 된다. 
그리고 send() 메서드에 보내려는 데이터정보를 넣어주면 된다.

xhttp.open('POST', 'demo_post.asp', true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send('fname=Henry&lname=Ford');

비동기식 - True or False

ajax를 사용하려면 3번째 파라미터는 무조건 true 여야 한다

xhttp.open('GET', 'ajax_test.asp', true);

Async = true

xhttp.onreadystatechange = function(){
    if(xhttp.readyState == 4 && xhttp.status == 200){
        document.getElementById('demo').innerHTML = xhttp.responseText;
    }
};
xhttp.open('GET', 'ajax_info.txt', true);
xhttp.send();

Async = false

xhttp.open('GET', 'ajax_test.asp', false);
async=false 로 사용하게 되면 더이상 ajax를 사용하지 않는 다는 선언이다. 
이렇게 서버로 요청을 하게 되면 서버에서 응답이 오기 전까지 화면에서 아무것도 할 수 없는 상황이 발생한다.

xhttp.open('GET', 'ajax_info.txt', false);
xhttp.send();
document.getElementById('demo').innerHTML = xhttp.responseText;

XMLRequest readyState 값

XMLRequest Status 값

Ajax 서버 응답

서버로부터 응답을 받기 위해서는 XMLHttpRequest 객체의 reponseText 또는 reponseXML 속성을 사용한다.

속성설명

responseText 응답 데이터를 string으로 받는다.
responseXML 응답 데이터를 XML로 받는다.

reponseText 속성

document.getElementById('demo').innerHTLM = xhttp.responseText;

responseXML 속성

// cd_catalog.xml이 있다고 가정했을 때, 파일을 요청하고 응답으로온 데이터 파싱하기

xmlDoc = xhttp.responseXML;
txt = '';
x = xmlDoc.getElementsByTagName('artist');
for(i = 0; i < x.length; i++){
    txt += x[i].childNodes[0].nodeValue + '<br />';
}
document.getElementById('demo').innerHTML = txt;

Ajax 이벤트

onreadystatechange 이벤트

XMLHttpRequest 객체는 상태정보를 가지고 있는데, readyState 속성이 그 값을 가지고 있다.

그리고 우리는 이 상태 정보를 보고 응답이 왔는지, 그 응답이 정상적으로 왔는지 확인할 수 있다.

 readyState 가 변할 때마다 항상 발생하는 이벤트가 있는데 그것이 바로 onreadystatechange 이벤트 이다. XMLHttpRequest 객체의 중요한 세 가지 속성은 아래와 같다.

onreadystatechange 이벤트가 발생하고 readyState4이며 status200이면

정상적으로 요청이 처리되어 응답이 온 경우이다.

function loadDoc(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if(xhttp.readyState == 4 && xhttp.status == 200){
            document.getElementById('demo').innerHTML = xhttp.responseText;
        }
    };
}
onreadystatechange 이벤트는 한번의 요청을 할 때 총 5번 발생한다. (readyState가 0에서 4까지 바뀌므로)

Callback 함수 사용하기

callback 함수는 다른 함수의 파라미터로 넘겨지는 함수를 말한다. 만약 웹사이트에 하나 이상의 Ajax 작업이 있다면, 단 하나의 표준 함수를 만들어서 XMLHttpRequest 객체를 생성하고 각자의 Ajax 작업이 있을 때마다 이 표준함수에서 호출함으로써 코드를 단순화 할 수 있다. 표준함수는 각각의 Ajax 작업을 하는 함수를 파라미터로 넘겨받아 이를 처리하게 된다.

 

function loadDoc(cFunc){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if(xhttp.readyState == 4 && xhttp.status == 200){
            cFunc(xhttp);
        }
    };
}

Ajax 데이터베이스

showCustomer() 함수

사용자가 드랍다운 리스트에서 고객을 선택하면, showCustomer() 함수가 호출되어 실행된다. 이 함수는 onchange 이벤트 가 발생하면 호출되도록 되어있다.

function showCustomer(str){
    var xhttp;
    if(str == ''){
        document.getElementById('txtHint').innerHTML = '';
        return;
    }
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if(xhttp.readyState == 4 && xhttp.status == 200){
            document.getElementById('txtHint').innerHTML = xhttp.responseText;
        }
    };
    xhttp.open('GET', 'getcustomer.asp?q='+str, true);
    xhttp.send();
}

showCustomer() 함수는 아래와 같은 작업을 한다.

  • customer가 선택이 되었는지 검사한다.
  • XMLHttpRequest 객체를 생성한다.
  • 서버로부터 응답을 받고나서 실행될 함수를 정의한다.
  • 서버에 있는 파일로 요청을 보낸다.
  • 요청을 보낼 때 파라미터 ‘q’와 드랍다운 리스트에서 읽어온 str을 URL에 추가.

 

반응형