如何使用“container / placeholder”div中的链接使用AJAX加载内容

时间:2015-04-13 00:33:29

标签: javascript php jquery ajax

我想使用位于同一div内的链接使用AJAX加载内容。我从here采用了一个很好的例子,它使用了历史API,也是SEO友好的。

以下是结构的摘录:

HTML

<body>

    <?php
      $page = 'home'; 
      include('inc/navbar.php'); //Nav bar contains links that will load inside the Placeholder
    ?>

    <div class="placeholder">

      <!-- THIS CONTENT WILL BE LOADED WITH AJAX -->
      <!-- THIS IS WHERE I'M TRYING TO LINK TO INTERNAL PAGES -->

    </div>

    <?php include('inc/footer.php'); ?>

</body>

导航HTML包含

<ul class="nav">
  <li <?php echo ($page == 'page-one') ? "class='active'" : ""; ?>><a href="page-one">Link to Page 1</a></li>
  <li <?php echo ($page == 'page-two') ? "class='active'" : ""; ?>><a href="page-two">Link to Page 2</a></li>
  <li <?php echo ($page == 'page-three') ? "class='active'" : ""; ?>><a href="page-three">Link to Page 3</a></li>
</ul>

JAVASCRIPT

var History = {
    run: function() {
        if(History.detectSupport()){
            this.content($('.nav a'));
            this.pop();
        }
    },
    detectSupport: function() {
        return !!(window.history && history.pushState);
    },
    content: function(el) {
        el.on('click', function(e){
            e.preventDefault();
            var url = $(this).attr('href');

            $('.placeholder').html('<div class="loading" />');

            el.parent().removeClass('active');
            $(this).parent().addClass('active')

            History.ajax(url);
            history.pushState(null, document.title, url);

            if (typeof _gaq !== "undefined" && _gaq !== null) {
                _gaq.push(['_trackPageview', url]);
            }

        });
    },
    pop: function() {
        window.onpopstate = function() {
            var url       = location.pathname,
                pathArray = url.split('/');

            History.ajax(url);

            $('.nav li').removeClass('active');
            if(pathArray[2] == ''){
                $('.nav li:first').addClass('active');
            }else {
                $('a[href="'+pathArray[2]+'"]').parent().addClass('active');
            }
        }
    },
    ajax: function(url) {
        $.ajax({
            url: url,
            type: "GET",
            dataType: "html",
            success: function(res) {
                $('.placeholder').remove('.loading');
                $('.placeholder').html($(res).find('.placeholder').html());
                document.title = $(res).filter("title").text();
            }
        });
    }
}

//This function does all the magic
$(function() {
    History.run();
});

我试图在placeholder DIV中运行该功能并且工作正常。问题是当我尝试在页面之间切换时,在页面完全加载之前我有一些奇怪的闪烁。另一个解决方法也已完成,但它不加载历史API支持所需的变量,并获得SEO友好的URL。

任何帮助都将非常感谢!

0 个答案:

没有答案