2012-08-06 71 views
1

我试图让我找到的代码这里在我的网站上工作。正如预期的那样,该网站是作为一个普通的网站建立的,发送HTTP请求进行页面更改,现在我试图将其升级到完整的ajax。获取此pushState /加载内容代码工作

下面的代码执行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/

+0

这将使它更容易回答这个问题,如果你可以在http://jsfiddle.net/ – valentinas 2012-08-06 02:38:09

+0

上提供一个工作示例它将如何做到这一点,因为它使用的是一个Ajax请求?我无法加载那里的跨域内容。另外,我已经提供了源站点,应该不够吗? – CoreyRS 2012-08-06 02:46:27

+0

jsfiddle有一个模拟AJAX请求的API:http://doc.jsfiddle.net/use/echo.html – valentinas 2012-08-06 02:47:55

回答

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链接没有一个路径,所以一定要确保他们在相同的目录等

+0

我不知道,我只是从网站上复制代码哈哈。从来没有使用这种类型的Ajax加载,虽然读了它,不知道应该/不应该改变。如果你可以修改它,请做。 – CoreyRS 2012-08-06 03:16:53

+0

@CoreyRS - 简化了一下,试用一下,并保持控制台打开(F12)检查错误。 – adeneo 2012-08-06 03:26:44

+0

mwuahahahaha,你是个传奇人物。 – CoreyRS 2012-08-06 03:35:24