次の投稿の一番上の回答のコードを使用しています。
Web サイトを ajax 化する方法を理解するのに助けが必要
例に示すように、.html ページで試してみると、正しく動作しています。ただし、私のページはphpです。URLが更新されたときに.phpではなく.htmlとして表示されることを除いて、すべてがphpページで正常に機能しています。
私が言及した答えから取られたコードでは:
<script type="text/javascript">
var directory = 'content/'; //directory of the content we want to ajax in
var state = History.getState();
//for when they click on an ajax link
$('.ajaxify').on('click', function(e){
var $this = $(this);
var href = $this.attr('href'); // use the href value to determine what content to ajax in
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
e.preventDefault(); // we don't want the anchor tag to perform its native function
});
//for when they hit the back button
$(window).on('statechange', function(){
state = History.getState(); // find out what we previously ajaxed in
$.ajax({
url: directory + state.title + '.html', //create our path
dataType: 'html',
success: function(data) {
$('#content').html(data);
}
});
});
</script>
変えてみました
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
に (.html を .php に変更):
$.ajax({
url: directory + href + '.php', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.php'); // change the url and add our ajax request to our history
}
});
ただし、これは効果がありません。HTMLの変更も試みました:
<ul id="nav">
<li id="home-link"><a href="home" class="ajaxify" title="Home">Home</a></li>
<li id="work-link"><a href="work" class="ajaxify" title="Work">Work</a></li>
<li id="labs-link"><a href="labs" class="ajaxify" title="Labs">Labs</a></li>
<li id="blog-link"><a href="blog" class="ajaxify" title="Blog">Blog</a></li>
</ul>
<div id="content">Home Content</div>
に(.phpをhrefに追加):
<ul id="nav">
<li id="home-link"><a href="home.php" class="ajaxify" title="Home">Home</a></li>
<li id="work-link"><a href="work.php" class="ajaxify" title="Work">Work</a></li>
<li id="labs-link"><a href="labs.php" class="ajaxify" title="Labs">Labs</a></li>
<li id="blog-link"><a href="blog.php" class="ajaxify" title="Blog">Blog</a></li>
</ul>
<div id="content">Home Content</div>
ただし、これにより、ページの読み込みが完全に機能しなくなります。アドバイスをいただければ幸いです。ありがとう!