4차산업혁명의 일꾼/웹개발
javascript/jsp및 프론트 복습
르무엘
2024. 6. 17. 18:48
jquery는 모바일 때문에 지양하는 추세이긴 하는데 그래도 좋은 면이 많아서, 웹프론트에서 계속 쓰는데, DOM조작하고 이벤트처리, ajax지원하는 것들을 복습하니 새롭다. javascript보다 좀더 섬세한 DOM조작이 가능하고, 애니메이션효과와 ajax요청이 쉽다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XMLHttpRequest Example</title>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="dataContainer"></div>
<script>
document.getElementById('loadData').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
document.getElementById('dataContainer').innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
}
};
xhr.send();
});
</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>jQuery AJAX</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="dataContainer"></div>
<script>
$(document).ready(function(){
$("#loadData").click(function(){
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
type: "GET",
success: function(data){
$("#dataContainer").html(`
<h3>${data.title}</h3>
<p>${data.body}</p>
`);
},
error: function(error){
console.log("Error:", error);
}
});
});
});
</script>
</body>
</html>
이렇게 간단하게 요청 할 수 있다.
fetch는 promises를 사용하여 ajax 요청을 더욱 간단하고 직관적으로 처리할 수 있게 한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API Example</title>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="dataContainer"></div>
<script>
document.getElementById('loadData').addEventListener('click', function() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
document.getElementById('dataContainer').innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
fetch가 코드가 간결하여 가독성이 좋고 비동기 요청을 더 쉽게 다룰수 있어 좋으나 구형브라우저에서 지원되지 않는다.
jsp는 jquery가 link 라이브러리로 무거워지는 것과 성능 때문에 지양되는 것과 다르게 코드의 가독성과 유지보수면에서 안좋아서 지양하는 추세이다.
LIST