保存通过 Ajax 加载内容的页面状态

Saving the state of a page with content loaded via Ajax

背景

每当单击项目 link 时,我都会通过 Ajax 将我的项目(帖子)加载到首页的 div 中。响应很好,我已经设法让 pushState() 出色地工作。

问题

我在加载项目后保存状态时遇到问题。

加载项目时,url 从 example.com 变为 example.com/title-of-post。我想在加载项目 (example.com/title-of-post) 时保存状态,以便当用户在地址栏中输入 example.com/title-of-post 时,页面会加载 div 中加载的项目。

注意:example.com/title-of-post 用于重定向到 example.com/projects/title-of-post 但我在上面做了一个 htaccess 重定向。

例子

This page 是我试图实现的一个很好的例子,尽管我不想在 url 中使用主题标签。请注意,当您访问 url 时,相应的项目 (dubai) 已经加载。

我做了什么(使用History.js)

$('.post-link').on('click', function(e) {
    e.preventDefault();

    var post_id = $(this).data('id'),
        projectTitle = $(this).data('title'), 
        projectSlug = $(this).data('slug'), 
        ajaxURL = site.ajaxurl; 

    $.ajax({
        type: 'POST',
        url: ajaxURL,
        context: this,
        data: {'action': 'load-content', post_id: post_id },
        success: function(response) {

            // Load the response from the Ajax call
            $('#project-container').html(response);

            // Make history
            var stateDataObj = { project: projectSlug };
            History.pushState(stateDataObj, site.title, site.url + '/' + projectSlug);

            // Revert to our previously saved state
            History.Adapter.bind(window, 'statechange', function(){ // Note: We are using statechange instead of popstate
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                var stateDataObj = State.data;
                $(this).closest('#main').find('#project-container').html(response);
            });

            return false;
        }
    });
});

这是我的 WordPress 循环。

<div id="project-wrapper">
    <a href="#" class="close-button">&times;</a>
    <div id="project-container"></div>
</div>

<div id="projects-list">

<!-- Start the loop -->
<?php $home_query = new WP_Query('post_type=projects');

while($home_query->have_posts()) : $home_query->the_post(); ?>

    <article class="project">
        <?php the_post_thumbnail( 'home-thumb' ); ?>
        <div class="overlay">
            <a class="post-link expand" href="<?php the_permalink(); ?>" data-id="<?php the_ID(); ?>" data-title="<?php the_title(); ?>" data-slug="<?php global $post; echo $post->post_name; ?>">+</a>
        </div>
    </article>

<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>

</div><!-- #projects-list -->

看到了 url 的问题。它在浏览器加载之前就已解决,因此使用 url 位置而不是查询变量更加困难。

但要做到这一点,使用 $_SERVER[REQUEST_URI] 排除主机名获取当前 url 然后你可以将它匹配到你想要加载的任何项目并使用 php 加载。

您需要以与重写规则略有不同的方式执行此操作。在尝试加载 url 并重定向到 frontpage 之前,您需要一个挂钩到 init 的函数来捕获 url 。您还需要通过会话或 cookie 传递 url 信息。

如果您只是使用查询变量 ?name=page,您可以跳过重定向等。您的保存状态将使用一个简单的 js 函数。希望我改变了你的想法:)