1

我试图让我在这里找到的代码在我的网站上工作。正如预期的那样,该站​​点是作为一个普通站点构建的,发送页面更改的 HTTP 请求,现在我正在尝试将其升级到完整的 ajax。

下面的代码执行 pushState,后退/前进按钮工作,但我无法更改页面内容。有人知道我要去哪里错了吗?

<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>

编辑:

抱歉,链接似乎从未插入。

文章:http ://www.seomoz.org/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate 工作示例:http ://html5.gingerhost.com/

4

1 回答 1

1

你确定这是对的:

$.getJSON("post.php", {cid: url, format: 'json'}, function(json) {
    $.each(json, function(key, value){
        $('#wrapper').load(href);
    });
});   

首先,您执行 ajax 调用以获取一些 json 数据,然后迭代该 json 数据(假设它返回),并且在每次迭代中,您所做的只是对您之前设置的相同 href 进行另一个 ajax 调用,这是一个全局变量您已经发送了对 loadContent 的调用,并且可以访问url,因为不需要全局,并且href似乎没有从您的 popstate 事件中获得新值,所以它只会获得最后点击的页面吗?

另外,如果您不打算使用数据,为什么要遍历 json,并且在每次迭代时都执行相同的 ajax 调用?

编辑:

这将是很多猜测,但尝试简化一点:

$(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);
}
​

您的 HTML 链接没有路径,因此请确保它们位于同一目录中等。

于 2012-08-06T03:14:14.523 回答