背景
每当点击项目链接时,我都会通过Ajax将我的项目(帖子)加载到首页的div
。答案很好,我设法使pushState()
工作得非常好。
问题
我在加载项目时遇到了保存状态的问题。
加载项目时,网址会从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是我尝试实现的一个很好的例子,尽管我不想在网址中使用主题标签。请注意,当您访问该网址时,相应的项目(迪拜)已经加载。
我做了什么(使用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">×</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 -->
答案 0 :(得分:0)
看到它的问题所在的网址。它在浏览器加载之前解析,因此使用url位置而不是查询变量更加困难。
但要做到这一点,使用$_SERVER[REQUEST_URI]
排除主机名获取当前网址,然后您可以将此匹配到您要加载和使用php加载的任何项目。
您需要执行与重写规则略有不同的操作。在尝试加载url并重定向到首页之前,您需要一个挂钩到init的函数来捕获url。您还需要沿会话或cookie传递URL信息。
如果您只是使用查询var ?name=page
,您可以跳过重定向等。您的保存状态将适用于简单的js函数。希望我改变了主意:)。