SSR(Server Side Rendering)
서버 측에서 렌더링 마친 상태로 데이터가 결합된 화면을 클라이언트에 전달하는 방식 (JSP/Servlet 등)
- 새로운 페이지로 이동할 때마다 요청하기 때문에 깜박거리는 현상 존재
- SPA(Single Page Application) 기법이 대두되면서 CSR 방식이 각광
CSR(Client Side Rendering)
서버가 요청을 받으면 클라이언트에 각종 리소스를 보내주고 클라이언트가 그것을 받아 렌더링 하는 방식 (ajax, fetch 등)
- 최초 요청 시 HTML을 비롯한 CSS, JavaScript 등 각종 리소스를 받아오고 이후에는 서버에 데이터만 요청
- 자바스크립트로 뷰를 컨트롤
- 초기 이후 다른 페이지로의 이동시에는 SSR 보다 빠른 페이지 전환 속도와 더 나은 사용자 경험을 제공
- 초기 페이지는 아무것도 없는 빈 페이지
CSR 방식으로 HTML에서 HTML을 불러올 때 사용하는 jquery 함수 load()
$("#monthly").load("calender/N1001.html", function () {
// 해당 html 파일을 로드 후 실행할 코드 작성
});
ajax
ajax 를 함수화하여서 Promise 객체를 이용하는 방법으로 사용하는 법
.done() 말고도 .always() .fail() .then() 이 있다.
Promise객체를 이용하다 보니 계속해서 체인해서 done을 사용함으로써 순서대로 호출되도록 할 수 있다.
function ajax_calender_info(member_id, sel_year, sel_month) {
let year_month = "" + sel_year + (sel_month < 10 ? "0" + sel_month : sel_month)
return $.ajax({
url: 'http://localhost:8081/api/calender/info/' + member_id + '/' + year_month,
type: "GET",
dataType: 'json',
headers: {
"Authorization": "Bearer " + getCookie("jwt")
},
error: function (jqXHR) {
if (jqXHR.status == 401) {
tokenCall2(false).done(function () {
ajax_calender_info(member_id, sel_year, sel_month)
});
}
}
});
}
ajax_calender_info(member_id, sel_year, sel_month).done(function (response) {
let isUpdate = false;
for (result of response) {
let date = parseInt(result.calender_day.substring(6, 8));
if (sel_day === date) {
isUpdate = true;
}
}
let send_data = {
"member_id": member_id,
"calender_day": sel_year + (sel_month < 10 ? "0" + sel_month : sel_month) + (sel_day < 10 ? "0" + sel_day : sel_day),
"is_star": starList[sel_day],
"memo": inputText
}
// 수정
if (isUpdate) {
ajax_calender_info_set(send_data).done(function () {
memo_init(member_id, sel_year, sel_month, sel_day, sel_category, inputText);
})
// 신규
} else {
ajax_calender_info_new(send_data).done(function () {
memo_init(member_id, sel_year, sel_month, sel_day, sel_category, inputText);
});
}
});
날짜 치환 함수
// [S] 날짜 관련 함수
function year_month_date_dot(date) { // 포맷 yyyy.MM.dd
var result = date.getFullYear() + '.'
result += (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) + '.' : (date.getMonth() + 1) + '.'
result += date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return result;
}
function year_month_date_none(date) { // 포맷 yyyyMMdd
var result = date.getFullYear()
result += (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1)
result += date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
return result;
}
function year_month_dot(date) { // 포맷 yyyy.MM
var result = date.getFullYear() + '.'
result += (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1)
return result;
}
function month_date_dot(date) { // 포맷 MM.dd
var result = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) + '.' : (date.getMonth() + 1) + '.'
result += date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return result;
}
function month_date_none(date) { // 포맷 MMdd
var result = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1): (date.getMonth() + 1)
result += date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return result;
}
function hours_minute_col(date) { // 포맷 HH:mm
var result = (date.getHours() + 1) < 10 ? "0" + (date.getHours() + 1) + ':' : (date.getHours() + 1) + ':'
result += date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
return result;
}
function year_month_date_hours_min(date) { // 포맷 yyyy.MM.dd HH:mm
var result = date.getFullYear() + '.'
result += (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) + '.' : (date.getMonth() + 1) + '.'
result += date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " "
result += date.getHours() < 10 ? "0" + date.getHours() + ":" : date.getHours() + ":"
result += date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
return result;
}
function year_month_date_dash(date) { // 포맷 yyyy-MM-dd
var result = date.getFullYear() + '-'
result += (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) + '-' : (date.getMonth() + 1) + '-'
result += date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return result;
}
function toKor_dayOfWeek(dayOfWeek) { // 한글 요일
switch (dayOfWeek) {
case 0: dayOfWeek = '일요일'; break;
case 1: dayOfWeek = '월요일'; break;
case 2: dayOfWeek = '화요일'; break;
case 3: dayOfWeek = '수요일'; break;
case 4: dayOfWeek = '목요일'; break;
case 5: dayOfWeek = '금요일'; break;
case 6: dayOfWeek = '토요일'; break;
}
return dayOfWeek;
}
// [E] 날짜 관련 함수
Map 자료 구조 정렬(Array 정렬을 이용함)
// 1. Map 객체를 배열로 변환
let keyAscArray = [...mapObj];
let keyDescArray = [...mapObj];
// 2-1. 오름차순 정렬
keyAscArray.sort(); // Key값 기준 오름차순으로 정렬
valAscArray.sort((a, b) => a[1] - b[1]); // value값 기준 오름차순정렬
// 2-2. 내림차순 정렬
keyDescArray.sort().reverse(); // Key값 기준 내림차순으로 정렬
valDescArray.sort((a, b) => b[1] - a[1]); // value값 기준 내림차순정렬
// 3. 정렬한 배열을 Map 객체로 변환
let keyAscMap = new Map(keyAscArray);
let keyDescMap = new Map(keyDescArray);
// 실사용 한줄로
let keyAscMap = new Map([...mapObj].sort());
let keyDescMap = new Map([...mapObj].sort().reverse());
Map 순회 방법
myMap.forEach((value, key) => {
console.log("key: " + key + ", value: " + value);
});
for (const [key, value] of myMap) {
console.log("key: " + key + ", value: " + value);
}
for (const key of myMap.keys()) {
console.log(key);
}
for (const value of myMap.values()) {
console.log(value);
}
숫자 관련 함수
Number.toLocaleString('ko-KR') // 천단위 , 추가되어 출력됨 ex) 1,000,000.123
// * toLocalString() 함수는 Number 뿐만아니라 Date, Array, Object에도 쓸 수 있다.
// ** Array, Object에 사용 시 안에 들어가 있는 숫자, 날짜를 설정한 국가에 맞는 형태로 출력한다.
Number.toFixed(n) // 소숫점 n 자리 까지만 표기됨
Array 함수
pop() : 배열의 마지막 요소를 제거 후 리턴
push(ele) : 배열의 마지막에 새로운 요소 추가
sort() : 배열 요소 정렬// 기본값은 문자열 오름차순
*내림 차순으로 정렬: array.sort((a,b)=>{return b-a});
*셔플: arr.sort(()=>{return 0.5-Math.random()});
join() : 배열 안의 모든 요소를 문자열로 변환 후 반환 (toString()과 똑같음)
forEach() : 배열을 for in 반복문처럼 사용 가능
array.forEach(function (ele, idx, arr) { // 배열요소, 인덱스, 배열자체
console.log(ele, idx, arr);
});
map() : 기존의 배열에 특정 규칙을 적용해서 새로운 배열 생성
// 배열의 모든 값에 연산 일괄 적용
arr = [1, 2, 3];
arr.map(function (ele){
return ele * 3;
})
console.log(arr); // [3, 6, 9]
filter() : 특정 조건을 만족하는 요소를 추출해 새로운 배열 생성
array = [2, 4, 6];
array = array.filter(function (element, index, array) {
return element < 5;
});
console.log(array); // [2, 4]
every(), some() : 배열의 요소가 조건을 만족하는지 확인
// every는 모든 요소, some은 단 하나라도 조건에 부합하는지 확인 후 true or false 반환
array = [9, 10]
array.every(function (element, index, array){
return element < 10;
}); // false
array.some(function (element, index, array){
return element < 10;
}); // true
// 실사용
arr = ['a', 'b']
if(arr.every((element) => isNaN(element))) {
console.log('이 배열에는 숫자가 없습니다.');
}
arr = [1, 'a']
if(arr.some((ele) => isNaN(ele))){
console.log('이 배열에 숫자가 아닌 값이 포함되어있습니다.');
}
reduce() : 배열을 순회하면서 하나의 값으로 만드는 함수
// 배열의 합과 같은 연산할때 이용가능
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial); // output: 10
배열 중복 제거
// Set 객체를 이용하는 방법
let arr = [1,2,1,2]
arr = [...new Set(arr)];
console.log(arr); // [1, 2]
// filter 를 이용하는 방법
let arr = [1,2,1,2]
arr = arr.filter((ele, idx) => arr.indexOf(ele) === idx);
console.log(arr);
JSON
JSON.stringify(Object) : 자바스크립트 객체를 JSON 문자열로 변환
// 자바스크립트 Object를 JSON 문자열로 변환하여 ajax body에 담아 보낼 때 사용됨
let send_data = {"name": "홍길동", "age": 28};
function ajax_calender_info_set(send_data) {
return $.ajax({
url: 'http://localhost:8081/api',
type: 'POST',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(send_data),
headers: {
"Authorization": "Bearer " + getCookie("jwt")
}
});
}
// ajax 호출 완료 후 dataType: 'json'을 주지 않을 경우 혹은 JSON문자열로 반환된다면 JSON.parse()를 해줘야한다.
let str = '{"name": "홍길동", "age": 28}';
str = JSON.parse(str) // JSON 문자열을 자바스크립트 객체로 변환
console.log(str.name, str.age); // 홍길동 28
'회고록(TIL&WIL)' 카테고리의 다른 글
TIL 2023.06.26 HMAC(keyed-Hash Message Authentication Code) (0) | 2023.06.26 |
---|---|
TIL 2023.06.19 전문통신(Fixed Length Format) (0) | 2023.06.19 |
TIL 2023.03.22 Spring Security, React-Redux, Scheduling (0) | 2023.03.22 |
2023.03.20~2023.03.21 SVN - Jenkins Windows 로컬 서버 CI/CD (0) | 2023.03.21 |
TIL 2023.03.21 암호화, JWT, Spring Security (0) | 2023.03.21 |