FrontEnd
5/19 - JQuery, Ajax
Jiwon_Loopy
2025. 6. 1. 16:09
반응형
목차
Ajax (Asynchronous Javascript And Xml)
- 비동기
- 비동기로 Ajax 요청 값 주고받기
let req = new XMLHttpRequest();
req.open('get','<<a href=https://jsonplaceholder.typicode.com/posts>https://jsonplaceholder.typicode.com/posts</a>>')
req.send();
console.log(req.response)
req.onreadystatechange = function() {
console.log('ready State 상태값 = ' + this.readyState)
console.log('status 상태값 = ' + this.status)
if(this.readyState === 4){
console.log(req.response)
}
}
- XMLHttpRequest의 readyState 값을 출력
- 이 값은 요청의 진행 상태(0~4)를 나타냄
- 0: UNSENT
- 1: OPENED
- 2: HEADERS_RECEIVED
- 3: LOADING
- 4: DONE
- 이 값은 요청의 진행 상태(0~4)를 나타냄
- XMLHttpRequest의 status 값을 출력
- 이 값은 요청의 성공 여부를 나타냄
- 200
- 성공
- 300
- URL 오류
- 400
- 클라이언트 오류
- 500
- 서버 오류
- 200
- 이 값은 요청의 성공 여부를 나타냄
비동기
- 비동기로 1초 뒤에 나오는 테스트
let req = new XMLHttpRequest();
req.open('get','<<a href=https://jsonplaceholder.typicode.com/posts>https://jsonplaceholder.typicode.com/posts</a>>')
// setTimeOut() : 특정 시간 후에 한 번 실행
// setInterval() : 특정 시간 간격 마다 실행 (계속)
// 1초 뒤에 한 번 실행
setTimeout(function() {
console.log('setTimeout')
}, 1000)
console.log('main 흐름')
- 비동기로 1초마다 나오는 테스트
let req = new XMLHttpRequest();
req.open('get','<<a href=https://jsonplaceholder.typicode.com/posts>https://jsonplaceholder.typicode.com/posts</a>>')
// setTimeOut() : 특정 시간 후에 한 번 실행
// setInterval() : 특정 시간 간격 마다 실행 (계속)
// 1초 뒤에 한 번 실행
setTimeout(function() {
console.log('setTimeout')
}, 1000)
console.log('main 흐름')
// 1초 마다 실행
setInterval(function() {
console.log('setInterval')
}, 1000)
console.log('main 흐름')
- 중지
- clearInterval(매개 변수)
- 매개변수는 setInteval의 리턴 값
- 응용해서 타이머 만들어 보기
- 시작, 종료
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
<label id="label" style="font-size: 50px;">0</label>
</p>
<button id="start">시작</button>
<button id="end">종료</button>
<script>
let req = new XMLHttpRequest();
req.open('get', 'https://jsonplaceholder.typicode.com/posts')
let cur = 0;
let curc = 0;
const button1 = document.querySelector("#start")
const button2 = document.querySelector("#end")
button1.onclick = function () {
culc = setInterval(function () {
cur++;
let label = document.querySelector("#label")
label.textContent = cur;
}, 1000)
}
button2.onclick = function () {
clearInterval(culc)
}
</script>
</body>
</html>
- ES8 이후 Promise() 코드
// Promise (ES8)
function test(func) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('문자열');
});
});
}
test().then(function(arg) {
console.log(arg);
});
console.log('main 흐름');
// 비동기를 동기적으로 처리
async function test2() {
let result = await test(function(arg) {
return arg;
});
console.log('test2:'+result);
};
test2();
- Async, Await
<script>
// Promise (ES8)
function test(func) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('문자열');
});
});
}
test().then(function(arg) {
console.log(arg);
});
console.log('main 흐름');
// 비동기를 동기적으로 처리
async function test2() {
let result = await test(function(arg) {
return arg;
});
console.log('test2:'+result);
};
test2();
</script>
- 실행 흐름
- test 함수 정의
- test 함수는 Promise를 반환합니다.
- Promise 내부에서 setTimeout을 사용해 비동기로 1초 뒤에 '문자열'을 resolve합니다.
- test() 실행
- test()를 호출하면 Promise가 반환되고, 바로 .then()이 연결됩니다.
- .then()의 콜백은 Promise가 resolve될 때(즉, 1초 뒤에) 실행됩니다.
- console.log('main 흐름') 실행
- 이 줄은 비동기 작업과 상관없이 바로 실행됩니다.
- test 함수 정의
- 실제 출력 순서
- test()가 호출되고, Promise가 만들어지지만 아직 resolve되지 않았으므로 .then()의 콜백은 대기 상태입니다.
- console.log('main 흐름')이 바로 실행되어 먼저 출력됩니다.
- 약간의 시간(기본적으로 0ms, setTimeout의 기본값) 후, Promise가 resolve되고 .then()의 콜백이 실행되어 **'문자열'**이 출력됩니다.
- fetch
- Promise 리턴
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
<label id="label" style="font-size: 50px;">0</label>
</p>
<button id = "start">시작</button>
<button id = "end">종료</button>
<script>
// ajax
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => console.log(json))
</script>
</body>
</html>
- 로딩 순서
```jsx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id = "parent">
<div id = "first">첫째</div>
<div id = "first">둘째</div>
<div id = "first">셋째</div>
<img src="/img/bbb.png" alt="큰 테스트 이미지">
</div>
<script>
window.onload = function() {
console.log('window.onload')
}
$(document).ready(function() {
console.log('document ready')
})
$(function() {
console.log('$ function')
})
</script>
</body>
</html>
```
객체 생성
- 객체 요소 생성해서 넣기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id = "parent">
<div id = "first">첫째</div>
<div id = "first">둘째</div>
<div id = "first">셋째</div>
</div>
<script>
$(document).ready(function() {
console.log('document ready')
// 요소 객체 생성 $(문자열)
$('<div>넷째<div>').appendTo("#parent");
$('#parent').append("<div>다섯째<div>")
$('#parent').after("<div>마지막째<div>")
$('#parent').before("<div>0번쨰<div>")
// insert, prepend, ...
})
$(function() {
console.log('$ function')
})
</script>
</body>
</html>
- 순서 바꾸기 (옮기기)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id = "parent">
<div id = "first">첫째</div>
<div id = "second">둘째</div>
<div id = "third">셋째</div>
</div>
<script>
$(document).ready(function() {
console.log('document ready')
// 요소 객체 생성 $(문자열)
$('<div>넷째<div>').appendTo("#parent");
$('#parent').append("<div>다섯째<div>")
$('#parent').after("<div>마지막째<div>")
$('#parent').before("<div>0번쨰<div>")
// insert, prepend, ...
$('#first').appendTo('#third')
})
$(function() {
console.log('$ function')
})
</script>
</body>
</html>
- 복제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id = "parent">
<div id = "first">첫째</div>
<div id = "second">둘째</div>
<div id = "third">셋째</div>
</div>
<script>
$(document).ready(function() {
console.log('document ready')
// 요소 객체 생성 $(문자열)
$('<div>넷째<div>').appendTo("#parent");
$('#parent').append("<div>다섯째<div>")
$('#parent').after("<div>마지막째<div>")
$('#parent').before("<div>0번쨰<div>")
// insert, prepend, ...
$('#first').appendTo('#third')
// 복제
$('#first').clone().appendTo("#third")
})
$(function() {
console.log('$ function')
})
</script>
</body>
</html>
이벤트
- 이벤트
- $(선택자).bind(’이벤트종류’,콜백)
- $(선택자).on(’이벤트종류,콜백’)
- $(선택자).click(콜백)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id = "parent">
<div id = "first">첫째</div>
<div id = "second">둘째</div>
<div id = "third">셋째</div>
</div>
<script>
$(document).ready(function() {
console.log('document ready')
// 요소 객체 생성 $(문자열)
$('<div>넷째<div>').appendTo("#parent");
$('#parent').append("<div>다섯째<div>")
$('#parent').after("<div>마지막째<div>")
$('#parent').before("<div>0번쨰<div>")
// insert, prepend, ...
$('#first').appendTo('#third')
// 복제
$('#first').clone().appendTo("#third")
$('#third').on('click', function(){
alert('클릭')
});
})
$(function() {
console.log('$ function')
})
</script>
</body>
</html>
- 이벤트 중지
- -off()
- 위 타이머 코드 JQuery식으로 바꾸기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<p>
<label id="label" style="font-size: 50px;">0</label>
</p>
<button id="start">시작</button>
<button id="end">종료</button>
<script>
let req = new XMLHttpRequest();
req.open('get', 'https://jsonplaceholder.typicode.com/posts')
$(function () {
let x;
$('#start').click(function () {
x = setInterval(function () {
$("#label").html(Number($("#label").html()) + 1)
}, 1000)
})
$("#end").click(function () {
clearInterval(x);
})
})
</script>
</body>
</html>
스타일 관련
- 매개변수 유무
- 매개변수 1개일 때 getter
- 매개변수 2개일 때 setter
- 매개 변수 유무 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<script>
$(function(){
// 매개변수가 있으면 setter, hong이라는 값을 인풋 안에 default로 넣어둔다.
$("#id").val('hong')
//
$("input[type='button']").on('click', function(){
let v = $("#id").val(); // 매개변수가 없으면 getter
if($("#id").val() === ''){
alert('아이디를 입력해주세요')
}
})
})
</script>
<input type="text" id ="id"><br>
<input type="button" value = "로그인">
</body>
</html>
값 관련
- 메서드 명();
- 메서드 명(duration);
- 메서드 명(duration, callback);
- 이벤트로 효과주기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<script>
$(function () {
$('#btn1').click(function () {
// 사라지는 효과
// $("#div1").hide();
// 보여지는 효과
// $("#div1").show();
// 토글
// $("#div1").toggle();
// 점점 커지거나 작아지면서 토글, duration을 주기
// $("#div1").toggle(20000);
// 슬라이드 효과
// $("#div1").slideDown();
// $("#div1").slideUp();
$("#div1").slideToggle();
});
});
</script>
<style>
#div1 {
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
<input type="button" id="btn1" value="효과">
<div id="div1"></div>
</body>
</html>
- 애니메이션
- animate(object);
- animate(object, duration);
- animate(object, duration, easing);
- easing 은 속도
- 빨라졌다가 느려지는 것
- animate(object, duration, easing, callback)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<script>
$(function () {
$('#btn1').click(function () {
// 애니메이션
// Interval등을 통해 주기적으로 움직이게 할 수 있음
$('#div1').animate({
left : 500
}, 3000).animate({
top : 500
},1000)
});
});
</script>
<style>
#div1 {
width: 100px;
height: 100px;
border: 1px solid #000;
/* 애니메이션을 사용하기 위한 relative */
position : relative;
}
</style>
<input type="button" id="btn1" value="효과">
<div id="div1"></div>
</body>
</html>
ajax 문법
- Ajax
- 내가 원하는 부분만 페이지 내에서 바꿀 수 있도록 함
- url로 html 가져와서 넣기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("#btn").click(function() {
$.ajax({
url : 'index.html', //http://127.0.0.1:/js/node_ex.html
success : function(res){
console.log(res)
$("#div1").html(res); // html로 들어옴
}
})
})
})
</script>
<title>Document</title>
</head>
<body>
<input type="button" value="ajax" id="btn">
<div id="div1"></div>
</body>
</html>
CORS (Cross Origin Resource Sharing, 교차 출처 리소스 공유)
- 네이버 같은 곳은 CORS 정책 때문에 접속할 수 없음
- 리스트로 가저온 내용 출력
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$("#btn").click(function() {
$.ajax({
url : 'https://jsonplaceholder.typicode.com/posts', //http://127.0.0.1:/js/node_ex.html
success : function(res){
let html = "";
html += "<table border = '1'>";
html += "<tr><th>번호</th><th>제목</th></tr>"
$.each(res, (i,e) => {
html += "<tr><td>"+e.id+"</td><td>"+e.title+"</td></tr>"
})
html += "</table>"
$("#div1").html(html)
}
})
})
})
</script>
<title>Document</title>
</head>
<body>
<input type="button" value="ajax" id="btn">
<div id="div1"></div>
</body>
</html>
- 파라미터를 주거나 , 메서드를 줄 수도 있다.
$.ajax({
url : '<https://jsonplaceholder.typicode.com/posts>', //http://127.0.0.1:/js/node_ex.html
data : {
page : 2
},
method : 'get',
- 캐싱, 비동기
cache : false, // 기본값 = true, 캐싱
async : true, // 기본값 = true, 비동기 여부
- 총 정리 (데이터 타입, error 추가)
$.ajax({
url : 'https://jsonplaceholder.typicode.com/posts', //http://127.0.0.1:/js/node_ex.html
data : {
page : 2
},
method : 'get',
cache : false, // 기본값 = true, 캐싱
async : true, // 기본값 = true, 비동기 여부
dataType : 'JSON', // 데이터 타입, HTML, JSON... 안 쓰면 자동으로 파싱해주기도 함
error : function(e){
console.log(e);
}, // 에러메세지
success : function(res){
let html = "";
html += "<table border='1'>";
html += "<tr>
<th>번호</th>
<th>제목</th>
</tr>"
$.each(res, (i,e) => {
html += "<tr>
<td>"+e.id+"</td>
<td>"+e.title+"</td>
</tr>"
})
html += "</table>"
$("#div1").html(html)
}
})
메모
- window.onload
- 전부 로딩
- add Listener “DomContent…”, $(function)
- 돔 요소만
- find
- 태그 내부에서 해당 요소를 찾음
- stop
- 이벤트 스택을 지움
728x90
반응형