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

时间:2013-08-30 15:02:50

标签: php jquery json pushstate popstate

短版

本教程中引用的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 pushstate example and 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>

1 个答案:

答案 0 :(得分:1)

content.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)(一个json有效的文件) )。并使用PHP中的application/json方法指定对header的响应的MIMEtype。