보라코딩

Day77_230417_ AJAX 본문

코딩/Servlet, JSP, MyBatis

Day77_230417_ AJAX

new 보라 2023. 4. 17. 18:12

14_Ajax_JavaScript.zip
0.01MB

 

15_Ajax_jQuery.zip
6.45MB

 

 

JSON

         

 

JSON 사용방법

 

 

JSON 타입

 

 

JSON과 XML 비교

: JSON이 심플

 

 

 

Ajax

 

 

 

 

xml로 ajax 사용

<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<name>우유</name>
<price>1000</price>
</product>
<product>
<name>음료수</name>
<price>800</price>
</product>
<product>
<name>녹차</name>
<price>1200</price>
</product>
</products>

 

 

 

 

<script>
/* Ajax 처리시 사용 객체 : XMLHttpRequest 객체 

XMLHttpReqeust.readyState : 데이터 전달 결과 상태를 표시
0 : 객체생성, open 안한 상태
1 : open 상태, send 안된 상태
2 : send 진행한 상태, 데이터가 발견되지 않은 상태
3 : 일부 데이터만 받은 상태 (데이터 받는 중)
4 : 데이터를 전부 응답받은 상태
XMLHttpReqeust.status : 응답 결과 값
200(성공), 4XX(클라이언트 오류), 5XX(서버측 오류)
*/

//1. XMLHttpRequest 객체 생성
let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
console.log("readyState: " + xhr.readyState + ", status: " + xhr.status);
if (xhr.readyState == 4 && xhr.status == 200) { //정상 응답 완료
alert("리턴받은 값(문자열) : " + xhr.responseXML);
console.log(xhr.responseXML);

// 전달받은 XML 사용
let xml = xhr.responseXML;
//let products = xml.getElementsByTagName("product");
let products = xml.querySelectorAll("product"); //선택자 사용방식
console.log(products);

//데이터 사용해서 화면에 표시
let output = "";
for (let product of products){
console.log(product);
let name = product.querySelector("name").innerHTML;
let price = product.querySelector("price").innerHTML;

console.log("name : " + name + ", price : " + price);
output += "<h2>" + name + " :" + price +"</h2>"
}

document.body.innerHTML += output; 

} else if (xhr.readyState == 4 && xhr.status != 200) {
console.error(">>> 오류발생 " + xhr.status);
}
};

//2. open("전송방식", "요청정보", 비동기여부)
xhr.open("GET", "data.xml", true);

//3. send() 실행
xhr.send();


</script>

 

 

 

json으로 ajax 사용

{"products" : [
{ "name" : "우유", "price" : 1000 },
{ "name" : "음료수", "price" : 800 },
{ "name" : "녹차", "price" : 1500 }
]
}

 

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax json</title>
</head>
<body>
<h1>Ajax JSON 데이터 요청 처리</h1>
<hr>

<script>
/* Ajax 처리시 사용 객체 : XMLHttpRequest 객체 

XMLHttpReqeust.readyState : 데이터 전달 결과 상태를 표시
0 : 객체생성, open 안한 상태
1 : open 상태, send 안된 상태
2 : send 진행한 상태, 데이터가 발견되지 않은 상태
3 : 일부 데이터만 받은 상태 (데이터 받는 중)
4 : 데이터를 전부 응답받은 상태
XMLHttpReqeust.status : 응답 결과 값
200(성공), 4XX(클라이언트 오류), 5XX(서버측 오류)
*/

// 1. XMLHttpRequest 객체 생성
let xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) { //정상 응답 완료
//alert("리턴받은 값(문자열) : " + xhr.responseText);
console.log(xhr.responseText); //JSON 문자열

//JSON.parse() 사용 : JSON 문자열 --> JS 객체 변환
let json = JSON.parse(xhr.responseText);
//alert(json);
console.log(json);
console.log(json.products);

//JavaScript 객체에서 속성값 사용(추출)
let products = json.products; // 배열데이터
let output = "";
for (let product of products){
output += "<h2>";
output += product.name + " : " + product["price"];
output += "</h2>";
}
output += "<hr>";

document.body.innerHTML += output; 


} else if (xhr.readyState == 4 && xhr.status != 200) {
console.error(">>> 오류발생 " + xhr.status);
}
};
// 2. open
xhr.open("GET", "data.json", true);

// 3. send 처리
xhr.send();

</script>
</body>
</html>

 


ajax 제이쿼리

 

Ajax(Asynchronous JavaScript and XML, 에이잭스 또는 아작스)
 비동기적인 웹 애플리케이션의 제작을 위해 이용하는 웹 개발 기법
 서버와 클라이언트가 속도를 맞출 필요가 없다.
 (클라이언트가 서버에게 요청하고 기다리지 않아도 된다.)
: 클라이언트가 비동기 방식으로 자바스크립트를 화면 전환 없이
  서버측에 자료를 요청하고 화면전환 없이 결과를 출력

  ///////////////////////////////////////////////////////////////////////
  웹상에서 정보를 전달하는 방법 : xml, json를 가장 많이 사용된다.
  xml : 사용자가 태그를 직접 만들어서 사용하는 것
  기상청 > 생활과 산업 > 인터넷 - RSS
  예) http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1111061500 

  
  json : key와 value(1:1 매칭)http://json.org
  json형식 : [{"키":"값","키":"값"}], [{"키":["값1","값2","값3"]}]
  예) http://openapi.seoul.go.kr:8088/sample/json/SeoulLibraryTime/1/5/
 ///////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////
1. jQuery.load(url,data,callback); ajax 기능으로 html 로그하고 DOM방식으로 삽입
*url : 서버측 위치, *data :가져올 데이터, callback:콜백함수
           
2. jQuery.get(url,data,callback,type) : get방식으로 원격페이지 로드
    jQuery.post(url,data,callback,type) : post방식으로 원격페이지 로드 
    
3. jQuery.getJSON() : get방식으로 json 데이터 로드          
jQuery.getScript() : get방식으로 script 데이터 로드
    
4. serialize() : form 요소에 전송할 데이터를 재가공
      => 'name1=value&name2=value'.. 액션페이지에 전송한다.
    serializeArray()
      => key1:value1,key2:value2, key3:value3...  JSON데이터로 변환하여 
5. ajaxComplete(function(){}) : Ajax통신이 완료(성공) 되면 함수에 있는 실행문 실행
 
6. jQuery.ajax({url,type,data, datatype});
   $.ajax({url,type,data, datatype});
   url : 서버 url (jsp, php, asp);
   type : get, post
   data : 서버쪽으로 전송되는 데이터
   dataType : 응답결과의 데이터 형태 (xml, html, json, text, script,....)
   success : 성공한 경우 
   error : 실패한 경우
   
   
   complete: 요청이 완료 되었을때
   contentType : 서버 전송시 content-type;
   
   
       
 


 
 

json_member.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax JSON</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(function(){
//$("#getDataBtn").on("click", function(){});
$("#getDataBtn").click(getJsonMembers);
});

function getJsonMembers(){
//alert("연결");
$.ajax("getJsonMembers", {
type : "get",
dataType : "json",
success : function(data){
alert("Ajax 처리 성공 - 응답받은 데이터 : " + data);
console.log(data);
console.log(data.list);

//전달받은 JSON 데이터 화면에 표시
let htmlTag = "";
let alist = data.list; //JSON 객체의 속성명 "list"값 추출
$.each(alist, function(index, member){
htmlTag += "<tr>";
htmlTag += "<td>" + this.idx + "</td>";
htmlTag += "<td>" + this.name + "</td>";
htmlTag += "<td>" + this.age + "</td>";
htmlTag += "<td>" + this.addr + "</td>";
htmlTag += "<td>" + this.regdate + "</td>";
htmlTag += "</tr>";
});

$("#tbody").html(htmlTag);

},
error : function(jqXHR, textStatus, errorThrown){
alert("Ajax 처리 실패 : \n" + 
"jqXHR.readyState : "+ jqXHR.readyState + "\n"
+ "textStatus : " + textStatus + "\n"
+ "errorThrown : " + errorThrown);
console.log("Ajax 처리 실패 : \n" + 
"jqXHR.readyState : "+ jqXHR.readyState + "\n"
+ "textStatus : " + textStatus + "\n"
+ "errorThrown : " + errorThrown);
}
});
}

</script>

</head>
<body>
<h1>Ajax JSON 데이터 요청 처리</h1>
<button id="getDataBtn">Ajax - JSON 데이터 가져오기</button>
<hr>
<table border>
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>나이</th>
<th>주소</th>
<th>날짜</th>
</tr>
</thead>
<tbody id="tbody">
<!-- <tr>
<td>1</td>
<td>쎈튜</td>
<td>33</td>
<td>동퇀</td>
<td>2023-04-17</td>
</tr> -->
</tbody>
</table>
<hr>
<a href="javascript:getJsonMembersName('싼쵸')">JSON 데이터 조회(이름)</a>

<script>
function getJsonMembersName(name) {
alert("getJsonMembersName(" + name + ") 실행" );

$.ajax("getJsonMembersName", {
type : "get",
data : "name=" + encodeURIComponent(name), //서버쪽으로 전달할 데이터
dataType : "json", //서버로부터 응답받을 데이터 타입
success : function(data){ //data : 응답받은 데이터 
alert("Ajax 성공 - 응답데이터 : " + data);
console.log(data);

//전달받은 JSON 데이터 화면에 표시
let htmlTag = "";
let alist = data.list; //JSON 객체의 속성명 "list"값 추출
$.each(alist, function(index, member){
htmlTag += "<tr>";
htmlTag += "<td>" + this.idx + "</td>";
htmlTag += "<td>" + this.name + "</td>";
htmlTag += "<td>" + this.age + "</td>";
htmlTag += "<td>" + this.addr + "</td>";
htmlTag += "<td>" + this.regdate + "</td>";
htmlTag += "</tr>";
});

$("#tbody").html(htmlTag);
},
error : function(){
alert("Ajax 실패!!!");
}
});
}

</script>

</body>
</html>


 

 
 
 
다시 공부하자

AJAX