Javascript 파일(/main.js)
// 뒤로가기시 페이지 새로고침
window.onpopstate = function(event) {
var np = document.location
BodyClassLoad(np);
}
// 페이지 시작시 a태그의 href 조정(타 도메인일경우 그대로 두고 같은 도메인일 경우 function 으로 처리되도록..)
window.onload = function(){
var abtn = document.querySelectorAll("a");
for(var i = 0; i < abtn.length; i++){
const loc = abtn[i].getAttribute("href");
if(loc.indexOf("://") == -1){
MoveHrefClick(abtn[i],loc);
}else{
if(loc.indexOf("://"+window.location.origin) > -1){
MoveHrefClick(abtn[i],loc);
}
}
}
}
// body class 조정 및 section 의 내용 교체
function BodyClassLoad(url){
var nc = "";
var mhref = "";
if(url.origin != undefined){
nc = url.href.substring(url.origin.length,url.origin.length+url.href.length);
}else{
nc = url;
}
mhref = nc;
if(nc.substring(0,1)=="/"){
nc = nc.substring(1,nc.length);
}
if(nc.substring(nc.length-1,nc.length)=="/"){
nc = nc.substring(0,nc.length - 1);
}
nc = nc.replace("/"," ");
document.querySelector("body").className = "BodyTag "+ nc;
var xhr = new XMLHttpRequest();
var loadurl = mhref;
if(loadurl.indexOf("?") == -1){
loadurl += "/main.php";
loadurl = loadurl .replace("//","/");
}else{
// PHP 페이지를 불러오도록 상황에 따라 변경
loadurl = loadurl .replace("?","main.php?");
}
xhr.open('GET', loadurl, true);
xhr.send();
xhr.onload = function(){
if (xhr.status == 200) {
document.querySelector("section").innerHTML = xhr.response;
} else {
// 실패
}
}
}
// a태그 href 비활성화 및 history 에 이전주소로 기록
function MoveHrefClick(el,href){
el.removeAttribute("href");
el.onclick = function(){
history.pushState({page: 1}, document.title, href);
BodyClassLoad(href)
}
}
PHP 페이지(/index.php, /A/index.php) : 복붙을 위해...
<?php
$relative_path = preg_replace("`\/[^/]*\.php$`i", "/", $_SERVER['PHP_SELF']);
$pathNode = explode( '/', $relative_path );
$bodyClass = "BodyTag";
for( $i = 0;$i < sizeof($pathNode); $i++){
if($pathNode[$i] != ""){
$bodyClass .= " ".$pathNode[$i];
}
}
$path1 = "Order";
$path2 = "";
$path3 = "";
if($bodyClass != "BodyTag"){
if(sizeof($pathNode)>1){
$path1 = $pathNode[1];
}
if(sizeof($pathNode)>2){
$path2 = $pathNode[2];
}
if(sizeof($pathNode)>3){
$path3 = $pathNode[3];
}
}else{
$bodyClass .= " ".$path1;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="/main.js" defer></script>
</head>
<body class="<?php echo $bodyClass; ?>">
<header><?php include $_SERVER["DOCUMENT_ROOT"]."/header.html"; ?></header>
<section><?php include $_SERVER["DOCUMENT_ROOT"].$relative_path."main.php"; ?></section>
<footer><?php include $_SERVER["DOCUMENT_ROOT"]."/footer.html"; ?></footer>
</body>
</html>
페이지구성(/header.html)
<a href="/">Home</a> <a href="/A/">A</a>
PHP 구성(/main.php)
<h2>Home</h2>
PHP 구성(/A/main.php)
<h2>A</h2>
댓글 없음:
댓글 쓰기