如何使用JSON格式的ajaxed内容实现pushState()和popState()


How to implement pushState() and popState() with ajaxed content in JSON format?

短版本

本教程中引用的content.php文件包含哪些内容?

http://moz.com/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate

带研究的长版本

上面的教程是我在通过Ajax加载内容但希望保留书签和浏览器前后导航功能的场景中实现pushState()popState()时遇到的最简洁的教程:

已经建立了一个演示页面作为概念验证:

http://html5.gingerhost.com/

其中源代码如下。

实现它需要几个中间步骤,但我并不完全熟悉:

  • 以JSON格式设置内容的PHP文件
  • 了解JSON格式

关于这个帖子的评论html5推送状态的例子和jquery';s$.getJSON建议使用Firebug查看HTTP请求响应,以便查看JSON格式。

加载Firebug后,选择控制台>全部,当我点击导航链接时,我会看到以下条目:

GET  http://html5.gingerhost.com/content.php?cid=%2F&format=json    200 OK  869ms
GET  http://html5.gingerhost.com/content.php?cid=%2Fseattle&format=json  200 OK  859ms
GET  http://html5.gingerhost.com/content.php?cid=%2Fnew-york&format=json  200 OK  837ms
GET  http://html5.gingerhost.com/content.php?cid=%2Flondon&format=json  200 OK  863ms

每个条目的"回复"选项卡中的相应内容采用JSON格式:

{"title":"Title value here","h1":"H1 value here","article #articletext":"<p>Lots of html here.<'/p><p>That includes escaped characters.<'/p>","#image":"<img class='"thumbnail'" alt='"'" src='"and_an_image.jpg'">"}

因此,经过一些研究,JSON格式似乎是:

{
"myArrayName": [
{ "Key1":"Value1" , "Key2":"Value2" },  // object one
{ "Key1":"Value3" , "Key2":"Value4" },  // object two 
{ "Key1":"Value5" , "Key2":"Value6" },  // object three
]
}

再加上一个"真实世界"的例子:

{
"myCDCollection": [
{ "Title":"Trash" , "Artist":"Alice Cooper" },  // object one
{ "Title":"Dr. Feelgood" , "Artist":"Motley Crue" },  // object two
{ "Title":"Cherry Pie" , "Artist":"Warrant" },  // object three
]
}

因此概念证明中的keys似乎是:

title
h1
article #articletext
#image

所以我的问题是,教程中引用的content.php文件需要什么内容?

这只是一个复制和粘贴JSON对象的问题,用逗号分隔吗?

它们需要封装在阵列中吗?

数组需要名称吗?

然后哪个被封装在大括号中?

PHP文件是否需要指定MIME媒体类型,如果需要,在哪里以及如何指定?

以下是概念验证的脚本:

<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('nav a').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("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>

php包含什么内容并不重要,它只需要返回一些内容,然后由javascript操作并加载到DOM中。你无法真正确定他的content.php包含什么,但考虑到页面的范围有限,这里有一种可能性:

<?php
    $page = $_GET['cid'];
    $pageData = array();
    switch ($page) {
        case '/':
            $pageData = array(
                'title' => 'Seattle - Part of a demo for #ProSEO',
                'h1' => 'Seattle',
                'article #articletext' => '<p>Seattle is the northernmost major city in the contiguous United States, and the largest city in the Pacific Northwest and the state of Washington. It is a major seaport situated on a narrow isthmus between Puget Sound (an arm of the Pacific Ocean) and Lake Washington, about 114 miles (183 km) south of the Canada - United States border, and it is named after Chief Sealth '"Seattle'", of the Duwamish and Suquamish native tribes. Seattle is the center of the Seattle-Tacoma-Bellevue metropolitan statistical area--the 15th largest metropolitan area in the United States, and the largest in the northwestern United States.<'/p><p>Seattle is the county seat of King County and is the major economic, cultural and educational center in the region. The 2010 census found that Seattle is home to 608,660 residents within a metropolitan area of some 3.4 million inhabitants. The Port of Seattle, which also operates Seattle-Tacoma International Airport, is a major gateway for trade with Asia and cruises to Alaska, and is the 8th largest port in the United States in terms of container capacity.<'/p>',
                '#image' => '<img class='"thumbnail'" alt='"'" src='"seattle.jpg'">'
            );
            break;
        case '/new-york':
            $pageData = array(
                'title' => 'New York - Part of a demo for #ProSEO',
                'h1' => 'New York',
                'article #articletext' => '<p>New York is the most populous city in the United States and the center of the New York metropolitan area, which is one of the most populous metropolitan areas in the world. New York City exerts a significant impact upon global commerce, finance, media, culture, art, fashion, research, technology, education, and entertainment. As the home of the United Nations Headquarters, it is also an important center for international affairs. The city is often referred to as New York City or the City of New York, to distinguish it from the state of New York, of which it is a part.<'/p>',
                '#image' => '<img class='"thumbnail'" alt='"'" src='"new-york.jpg'">'
            );
            break;
        case '/london':
            // similar code for london
            break;
        case '/seattle':
            // similar code for seattle
            break;
    }
    header('Content-Type: application/json');
    echo json_encode($pageData);
?>

实际上,它很可能从数据库等外部源检索页面数据。

这只是一个复制和粘贴JSON对象的问题,用逗号分隔吗?它们需要封装在阵列中吗

任何东西都不需要封装在数组中——无论它是如何到达那里的(您可以自己手动生成JSON),只要输出是这样的(JSON有效文件)。并使用PHP中的header方法指定对application/json的响应的MIMEtype。