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

Php 如何使用JSON格式的ajaxed内容实现pushState()和popState()?,php,jquery,json,pushstate,popstate,Php,Jquery,Json,Pushstate,Popstate,短版 本教程中引用的content.php文件有哪些内容 带有研究功能的长版本 在通过Ajax加载内容但希望保留书签和浏览器向后和向前导航功能的情况下,上面的教程是实现pushState()和popState()的最简洁的教程: 已设置演示页面作为概念证明: 其中源代码如下所示 实施它需要几个中间步骤,但我并不完全熟悉: 以JSON格式设置内容的PHP文件 理解JSON格式 这篇文章的评论建议使用Firebug查看HTTP请求响应,以便查看JSON格式 加载Firebug并选择Conso

短版

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

带有研究功能的长版本

在通过Ajax加载内容但希望保留书签和浏览器向后和向前导航功能的情况下,上面的教程是实现
pushState()
popState()
的最简洁的教程:

已设置演示页面作为概念证明:

其中源代码如下所示

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

  • 以JSON格式设置内容的PHP文件
  • 理解JSON格式
这篇文章的评论建议使用Firebug查看HTTP请求响应,以便查看JSON格式

加载Firebug并选择Console>All后,当我单击导航链接时,会看到如下条目:

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\">"}
添加一个“真实世界”的例子可以:

{
"myCDCollection": [
{ "Title":"Trash" , "Artist":"Alice Cooper" },  // object one
{ "Title":"Dr. Feelgood" , "Artist":"Motley Crue" },  // object two
{ "Title":"Cherry Pie" , "Artist":"Warrant" },  // object three
]
}
因此概念验证中的
键似乎是:

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>

//这就是魔法发生的地方
$(函数(){
$(“导航a”)。单击(功能(e){
$(“#加载”).show();
href=$(this.attr(“href”);
加载内容(href);
//历史,国家
history.pushState(“”,“新URL:”+href,href);
e、 预防默认值();
});
//此事件确保后退/前进按钮也能工作
window.onpopstate=函数(事件){
$(“#加载”).show();
log(“路径名:+location.pathname”);
loadContent(location.pathname);
};
});
函数加载内容(url){
//使用JQUERY加载内容
$.getJSON(“content.php”,{cid:url,格式:'json'},函数(json){
//此循环将所有内容放入正确的位置
$.each(json、函数(键、值){
$(键).html(值);
});
$(“#加载”).hide();
});
//这两行只是确保导航栏反映当前URL
$('li').removeClass('current');
$('a[href=“”+url+“]”)。parent().addClass('current');
}

无论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有效文件)。您可以使用PHP中的
header
方法指定对
应用程序/json
的响应的MIMEtype。

我也在寻找一段时间回答这个问题!我明白了,但我正在寻找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);
?>