본문 바로가기

프로그래밍/JavaScript

자바스크립트(JavaScript), 제이쿼리(jQuery) 페이지 이동(redirect)

안녕하세요. 루미오입니다.

JavaScript와 jQuery에서 페이지 이동 방법을 알아보겠습니다.

순서
● JavaScript의 페이지 이동
● jQuery의 페이지 이동
● Test Source Code

 

JavaScript의 페이지 이동

/* assign 방식 */
window.location = "https://loomio.kr";
window.location.href = "https://loomio.kr";		// window.location 동일함.
window.location.assign("https://loomio.kr");	// window.location 동일함.

/* replace 방식*/
window.location.replace("https://loomio.kr");

assign방식(2, 3, 4 Line) 은 History에 현재 페이지 정보를 저장하기 때문에 다시 현재의 페이지로 돌아올 수 있습니다. 하지만 replace 방식(7 Line) 은 현재 페이지 정보를 History에서 지우기 때문에 다시 현재 페이지로 돌아올 수 없습니다.

assign 방식(2, 3, 4 Line)과 replace(7 Line) 방식의 페이지 이동을 시뮬레이션 하면 아래와 같습니다.

▶ assign 방식

AB (assign) → C (history.back) → B

 

▶ replace 방식 (B page 정보를 History에서 지운다)

AB (replace) → C (history.back) → A

 

jQuery의 페이지 이동

$(location).attr("href", "https://loomio.kr");

jQuery에서는 $(location) 객체의 href attribute의 값을 변경하는 방식을 사용합니다. 하지만 jQuery 방식은 속도가 좀 느리기 때문에 pure JavaScript의 방식을 사용하기를 추천합니다.

 

Test Source Code

페이지 이동을 시뮬레이션할 HTML source code입니다. 각각 HTML 파일로 저장해서 테스트하세요. (A.html을 먼저 실행시키세요)

[A.html]

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
</head>
<body>
	<p>A.html</p>

	<a href="B.html">Let's Go B.html</a>
</body>
</html>

[B.html]

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
	<p>B.html</p>

	<button type="button" onclick="fLocation()">window.location = url</button>
	<button type="button" onclick="fHref()">window.location.href = url</button>
	<button type="button" onclick="fAssign()">window.location.assign(url)</button>
	<button type="button" onclick="fReplace()">window.location.replace(url)</button>
	<button type="button" onclick="fJqueryHref()">jQuery : $(location).attr('href', url)</button>

	<script type="text/javascript">
		function fLocation() {
			window.location = "C.html";
		}
		function FHref() {
			window.location.href = "C.html";
		}
		function fAssign() {
			window.location.assign("C.html");
		}
			function fReplace() {
			window.location.replace("C.html");
		}
		function fJqueryHref() {
			$(location).attr('href', "C.html");
		}
	</script>
</body>
</html>

[C.html]

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
</head>
<body>
	<p>C.html</p>

	<script type="text/javascript">
		alert('"C.html"입니다.\n이전 Page로 돌아갑니다.');
		history.back();	// history.back(-1); 과 동일함.
	</script>
</body>
</html>

 

감사합니다.

- 루미오 . LOOMIO -