Reputation: 2267
I'm trying to get the code I found here working on my site. As expected, the site was built as a normal site, sending HTTP requests for page changes, and now i'm trying to upgrade it to full ajax.
The code below executes the pushState, and the back/forward buttons work, but I can't get the content of the page to change. Anyone know where I'm going wrong?
<script>
$(function(){
$('a').on('click', function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("post.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$('#wrapper').load(href);
});
});
}
</script>
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>
<a href="link1.php"></a>
<a href="link2.php"></a>
<div id="wrapper-outer">
<div id="wrapper">
</div>
</div>
</body>
</html>
Edit:
Apologies, it seems the link never inserted.
Article: http://www.seomoz.org/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate Working example: http://html5.gingerhost.com/
Upvotes: 1
Views: 1943
Reputation: 318312
Are you sure this is right:
$.getJSON("post.php", {cid: url, format: 'json'}, function(json) {
$.each(json, function(key, value){
$('#wrapper').load(href);
});
});
First you do an ajax call to get some json data, then you iterate over that json data (assuming it returns) and on each iteration all you do is make another ajax call to the same href you set earlier, and that's a global variable that you've already sent in the call to loadContent, and would be accessable as url
instead, no need for a global, and href
does'nt seem to get a new value from your popstate event, so it will just get the last clicked page anyway ?
Also, why iterate over json if you don't intend to use the data, and just do the same ajax call on every iteration ?
EDIT:
This is going to be a lot of guessing, but try simplifying a little:
$(function() {
$('a').on('click', function(e) {
e.preventDefault();
var href = $(this).attr("href");
loadContent(href);
history.pushState({}, '', href);
});
$(window).on('popstate', function() {
loadContent(location.pathname);
});
});
function loadContent(url) {
$('#wrapper').load(url);
}
Your HTML links does not have a path, so make sure they are in the same directory etc.
Upvotes: 1