繁体   English   中英

更改URL并更新页面内容而无需重新加载

[英]Change url and update content of page without reload

它关系到我关于Web开发的最后一年的项目。 我想在不重新加载页面的情况下更改页面内容-我知道可以使用CSS / ajax或jquery来实现,但这只能通过在jquery中隐藏和显示或replaceWith()来实现。 我也希望更改网址。 我想实现类似于此页面的效果https://www.khanacademy.org/computing/computer-programming-当用户单击“对JS简介:绘图和动画”时,您将看到页面更改的URL和内容,但是页面却没有重装。

一个指南将不胜感激。 谢谢

一个小草稿:

**MY header.php**

 <script language="javascript" src="jquery-1.4.4.min.js"></script> <script> $(function(){ $("a[rel='tab']").click(function(e){ //e.preventDefault(); /* if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content; if commented, html5 nonsupported browers will reload the page to the specified link. */ //get the link location that was clicked pageurl = $(this).attr('href'); //to get the ajax content and display in div with id 'content' $.ajax({url:pageurl+'?rel=tab',success: function(data){ $('#content').html(data); }}); //to change the browser URL to 'pageurl' if(pageurl!=window.location){ window.history.pushState({path:pageurl},'',pageurl); } return false; }); }); /* the below code is to override back button to get the ajax content without reload*/ $(window).bind('popstate', function() { $.ajax({url:location.pathname+'?rel=tab',success: function(data){ $('#content').html(data); }}); }); </script> <div id='menu'> <a rel='tab' href='http://localhost/html5-history-api/menu1.php'>menu1</a> | <a rel='tab' href='http://localhost/html5-history-api/menu2.php'>menu2</a> | <a rel='tab' href='http://localhost/html5-history-api/menu3.php'>menu3</a></div> 

我的menu1.php(菜单2和3具有相同的代码)

 <?php if($_GET['rel']!='tab'){ include 'header.php'; echo "<div id='content'>"; } ?> menu1 content in menu1.php <?php if($_GET['rel']!='tab'){ echo "</div>"; include 'footer.php'; }?> 

我想要当我单击链接时-链接消失,并且仅显示诸如“ menu1 content in menu1.php”之类的内容,而页面上没有其他内容

如果您使用的是Chrome浏览器,则只需在该div上单击鼠标右键,然后使用“检查元素”选项即可。 这些是针对Web开发人员的便捷工具。 您提到的链接只是一个超链接,并且由于它是相同域下使用相同资源(css,js)的非常简单的静态页面,因此其加载速度非常快,并且您会感觉到没有页面加载。 在此处输入图片说明

我相信我从链接站点复制的此脚本解释了它们如何替换URL。 为了跟踪位置,他们使用localStorage来跟踪页面位置和其他内容。 转到页面并导航到您引用的链接。 然后打开控制台并键入localStorage。 当您按Banana时,您会看到我在说什么。

你可以这样做

localStorage.setItem( "itemName", item )
localStorage.getItem( "itemName" )

以下是源代码

<script type="text/javascript">
(function() {
        // If we arrived via a Facebook callback, it might have appended #_=_
        // to our URL. This can confuse our Backbone routers, so get rid of it.
        // http://stackoverflow.com/questions/7131909/facebook-callback-appends-to-return-url
        if (window.location.hash === "#_=_"){
            if (history.replaceState) {
                history.replaceState(null, null,
                        window.location.href.split("#")[0]);
            } else {
                window.location.hash = "";
            }
        }
    })();
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM