20. 8. 10.

Javascript 링크이동없이 URL 바꾸기

참고 : https://developer.mozilla.org/ko/docs/Web/API/History/pushState
p.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <style>
        a {
            background-color: #000;
            color: #fff;
            margin: 2px;
            cursor: pointer;
        }
    </style>
    <script>
        window.onload = function () {
            document.getElementById("btn1").addEventListener("click", function () {
                var page = 1;
                var state = { 'page_id': page, 'user_id': "" }
                var title = ''
                var url = 'page.html?page=' + page;
                history.pushState(state, title, url);
                // Javascript
                httpRequest = new XMLHttpRequest();
                if (!httpRequest) {
                    alert('XMLHTTP Fail');
                    return false;
                }
                httpRequest.onreadystatechange = function () {
                    if (this.readyState === XMLHttpRequest.DONE) {
                        if (this.status === 200) {
                            document.getElementById("view").innerHTML = this.responseText;
                        } else {
                            alert('Error');
                        }
                    }
                };
                httpRequest.open('GET', url);
                httpRequest.send();
            });

            document.getElementById("btn2").addEventListener("click", function () {
                var page = 2;
                var state = { 'page_id': page, 'user_id': "" }
                var title = ''
                var url = 'page.html?page=' + page;
                history.pushState(state, title, url);
                // JQuery
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (res) {
                        $("#view").html(res);
                    }
                });          
            });
        }
    </script>
</head>
<body>
    <a id="btn1">Page 1</a>
    <a id="btn2">Page 2</a>
    <div id="view"></div>
</body>
</html>

page.html
Page 입니다