-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpushState.php
68 lines (59 loc) · 1.77 KB
/
pushState.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
//figure out how many pages to make links for
$json = json_decode(file_get_contents('pages.json'));
$numberOfPages = count((array)$json);
//use get just the first part of the query parameter
if(isset($_GET)) {
//should be a regex
$currentPage = ($_GET['page']) ? explode(".",$_GET['page']) : '0';
$currentPage = $currentPage[0];
echo $currentPage;
//select the current page from the json object
$currentPageData = $json->$currentPage;
$title = $currentPageData->title;
$content = $currentPageData->content;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Single page application example</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
//find each list item
$("#pages>li").each(function(index, item){
$item = $(item);
//the dynamically created id originally came from the json object
var id = $item.attr("id");
$item.click(function(item){
item.preventDefault();
//when clicked, update the url
history.pushState("", "id", id + ".html");
//get the new content
$.ajax({
url: "pages.json",
dataType: 'json',
success: function(data){
//update the current html structure with the new content
$("#title").html(data[id].title);
$("#content").html(data[id].content);
}
});
});
});
});
</script>
</head>
<body>
<ul id="pages">
<?php foreach($json as $pageID => $page) { ?>
<li id="<?php echo $pageID;?>"><a href="<?php echo $pageID.'.html';?>"><?php echo $page->title;?></a></li>
<?php } ?>
</ul>
<?php if($title); {?>
<h1 id="title"><?php echo $title;?></h1>
<p id="content"><?php echo $content;?></p>
<?php } ?>
</body>
</html>