【发布时间】:2015-01-25 11:43:35
【问题描述】:
背景
每当单击项目链接时,我都会通过 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 时,相应的项目(迪拜)已被加载。
我做了什么(使用 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 -->
【问题讨论】:
-
不幸的是,它会尝试使用已经存在的重写规则来解析地址。所以你可以添加一个重写规则来重定向到你想要的页面并插入代码来读取 url 并加载你想要的项目。
-
好的,我可以用
htaccess制定重写规则,但是如何通过读取url 来加载我想要的项目?这就是我坚持的部分。我尝试在 Ajax 响应成功后立即设置状态,但我做错了。
标签: jquery ajax wordpress browser-history history.js