AJAX란, JavaScript의 라이브러리중 하나이며 Asynchronous Javascript And Xml(비동기식 자바스크립트와 xml)의 약자이다. 브라우저가 가지고있는 XMLHttpRequest 객체를 이용해서 전체 페이지를 새로 고치지 않고도 페이지의 일부만을 위한 데이터를 로드하는 기법 이며 JavaScript를 사용한 비동기 통신, 클라이언트와 서버간에 XML 데이터를 주고받는 기술이다.
즉, 쉽게 말하자면 자바스크립트를 통해서 서버에 데이터를 요청하는 것이다.
ex1)
xml 파일
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<model>세탁기</model>
<maker>삼성</maker>
<price>100</price>
</product>
<product>
<model>냉장고</model>
<maker>LG</maker>
<price>200</price>
</product>
<product>
<model>TV</model>
<maker>삼성</maker>
<price>300</price>
</product>
</products>
html
<div id="box1">
<button id="btn1">XML요청1</button>
</div>
script
<script>
$('#btn1').click(function(){
jQuery === $()
$.ajax({
/* 요청 */
type: 'get', // RequestMethod : get 또는 post
url: 'product1.xml', // 요청 URL (서버 경로를 작성)
async: true, // 비동기 통신(디폴트, 생략 가능)
/* 응답 */
dataType: 'xml', // 응답 데이터의 타입(text, xml, json 등)
success: function(resData){ // 매개변수 data로 응답 데이터가 전달됨 (resData = xhr.responseXML 또는 resData = xhr.responseText)
// 기존 목록 제거하기
$('#box1').find('ul').remove();
// resData에서 <product> 태그만 가져오기
var product = $(resData).find('product'); // JavaScript는 var product = resData.getElementsByTagName('product');
$.each(product, function(i, elem){
// <ul> 태그를 jQuery 객체로 생성
var ul = $('<ul>');
// <ul> 태그에 <li> 태그 만들어 넣기
ul.append($('<li>').text($(elem).find('model').text()));
ul.append($('<li>').text($(elem).find('maker').text()));
ul.append($('<li>').text($(elem).find('price').text()));
// <div id="box1">에 <ul> 태그 넣기
$('#box1').append(ul);
})
},
error: function(jqXHR){ // jqXHR 객체 : 에러에 관한 정보를 담고 있는 객체
// <div id="box1"> 태그를 jQuery 객체로 가져옴
var box1 = $('#box1');
box1.append($('<div>').text('응답코드' + jqXHR.status));
box1.append($('<div>').text('응답코드 텍스트' + jqXHR.statusText));
box1.append($('<div>').text('응답텍스트' + jqXHR.responseText));
}
})
})
</script>
ex2)
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product model="세탁기" maker="삼성" price="100" />
<product model="냉장고" maker="LG" price="200" />
<product model="TV" maker="삼성" price="300" />
</products>
<div id="box2">
<button id="btn2">XML요청2</button>
</div>
<script>
$('#btn2').click(function(){
$.ajax({
/* 요청 */
type: 'get',
url: 'product2.xml',
async: true,
/* 응답 */
dataType: "xml",
success: function(resData){
// <div> 태그를 jQuery 객체로 만들기
var productList = $('<div>').addClass('product_list');
// resData에서 <product> 태그를 가져온 뒤 순회하기
$.each($(resData).find('product'),function(i, elem){
// <div class="product"> 태그를 jQuery 객체로 만들기
var div = $('<div>').addClass('product');
// <div class="product"> 태그에 model, maker, price 속성(attribute)값 넣기
div.append($('<strong>').text($(elem).attr('model')));
div.append($('<em>').text($(elem).attr('maker')));
div.append($('<mark>').text($(elem).attr('price')));
// <div class="product_list"> 태그에 <div class="product"> 태그넣기
productList.append(div);
// <div id="box2"> 태그에 <div class="product_list"> 태그 넣기
$('#box2').append(productList);
})
},
error: function(jqXHR){
alert(jqXHR.status + '(' + jqXHR.statusText + ')');
}
})
})
</script>
css
<style>
#box2 div {
box-sizing: border-box;
border : 1px solid gray;
}
#box2 .product_list {
width: 400px;
display: flex;
justify-content: space-between;
}
#box2 .product {
width: 100px;
padding: 20px 10px;
text-align: center;
}
</style>
ex3)
json
[
{
"maker":"삼성",
"price":100,
"model":"세탁기"
},
{
"maker":"LG",
"price":200,
"model":"냉장고"
},
{
"maker":"삼성",
"price":300,
"model":"TV"
}
]
<div id="box3">
<button id="btn3">JSON요청1</button>
</div>
<script>
$('#btn3').click(function(){
$.ajax({
/* 요청 */
type: 'get',
url: 'product1.json',
async: true,
/* 응답 */
dataTypeL: 'json',
success: function(resData){ // resData = JSON.parse(xhr.responseText)
myFunc1(resData); // myFunc1 함수 호출
},
error: function(jqXHR){
alert(jqXHR.status + '(' + jqXHR.statusText + ')');
}
})
})
// myFunc1 함수 정의
function myFunc1(resData){
var productList = $('<div>').addClass('product_list');
$.each(resData, function(i, elem){
var ul = $('<ul>').addClass('product');
ul.append($('<li>').text(elem.maker));
ul.append($('<li>').text(elem.model));
ul.append($('<li>').text(elem.price));
productList.append(ul);
})
$('#box3').append(productList);
}
</script>
<style>
#box3 * {
box-sizing: border-box;
padding: 0;
margin: 0;
}
#box3 .product_list {
width: 400px;
display: flex;
justify-content: space-around;
border: 1px solid saddlebrown;
}
#box3 .product {
list-style-type: none;
padding: 20px 10px;
text-align: center;
border: 1px solid green;
}
</style>
ex4)
{
"products": [
{
"maker":"삼성",
"price":100,
"model":"세탁기"
},
{
"maker":"LG",
"price":200,
"model":"냉장고"
},
{
"maker":"삼성",
"price":300,
"model":"TV"
}
]
}
<div id="box4">
<button id="btn4">JSON요청2</button>
</div>
<script>
$('#btn4').click(function(){
$.ajax({
/* 요청 */
type: 'get',
url: 'product2.json',
async: true,
/* 응답 */
dataType: 'json',
success: function(resData){ // resData = JSON.parse(xhr.responseText)
$('#box4').find('table').remove();
myFunc2(resData); // myFunc2 함수 호출
},
error: function(jqXHR){
alert(jqXHR.status + '(' + jqXHR.statusText + ')');
}
})
})
// myFunc2 함수 정의
function myFunc2(resData){
var table = $('<table border="1"><thead><tr><td>순번</td><td>제조사</td><td>상품</td><td>가격</td></tr></thead></table>').addClass('products');
$.each(resData.products, function(i, elem){
var tr = $('<tr>');
tr.append($('<td>').text(i + 1));
tr.append($('<td>').text(elem.maker));
tr.append($('<td>').text(elem.model));
tr.append($('<td>').text(elem.price));
table.append(tr);
})
$('#box4').append(table);
}
</script>
'코딩기록 저장소 🐕 > 프론트(리액트, JS)' 카테고리의 다른 글
리액트 맛보기 (0) | 2023.10.26 |
---|---|
promise (0) | 2023.09.07 |
jQuery (0) | 2023.09.06 |
jQuery 1 (0) | 2023.09.06 |
jQuery class, event (0) | 2023.09.05 |