如何在不刷新页面的情况下改变URL

问没有具体业务场景的技术问题都是耍流氓,那在回答这个问题之前先简单介绍一下业务场景。

下午6点半,小 H写了一个下午的代码揉揉眼睛伸个懒腰,「今天终于能早点回去了,先刷会知乎歇会」。突然,产品 小U一脸淫笑飘了过来,小 H 略感不妙。
『嗨嗨~ 你这工作状态不饱和啊,有个小需求来看看~。现在需要做一个新闻展示页,主功能区块分为新闻列表和分页两部分。很简单,两天能搞定吧~』小 U 说。
小 H 看了看原型稿,心想确实不难。点击分页时把直接把分页参数传递给后台,页面刷新后台直接返回渲染后的数据就行了,模板写的好的话甚至 js 都不需要了。正当小 H 开口准备说说技术实现时,被小 U 打断…
『不过为了体验好一些,在用户点下一页的时候别刷新页面』小 U 说。
『不刷新页面没关系,我用 ajax 可以实现,不过时间嘛…』小 H 略有所思
『果然是大牛啊,能实现我就放心了。时间好商量,不过这个项目特别急,晚上加加油啊』,说完小 U 就飘走了。
『cao, 看来又走不成了』小 H 嘀咕着。
两分钟后小 U 又跑了过来,『刚才忘了跟你说了,用户点了下一页后地址栏的地址要跟着变,这时候刷新页面还能定位到当前页』
『 🐎x10000~~~』

整理下需求:

  1. 点击分页页码可实现无刷新页面加载
  2. 同时 URL 在数据加载后会发生变化展示对应页码
  3. 刷新页面(带页码参数)会定位到当前页码
  4. 当点击返回时可会到上个页面

效果如Demo 所示。

对于第1条,我们可以使用 ajax 动态获取对应页码的数据。

对于第2条,我们可以使用 html5的 api「history.pushState」,用于改变 URL。

对于第3条,我们可以根据 URL 中页码参数获取对应页码的数据再做展示。

对于第4条,可以使用 「window.onpopstate」来监听返回事件

那history.pushState如何使用呢?比如当用户点击页码按钮时,可使用 ajax 获取对应页码的数据,拼装 DOM 放到页面上,然后调用下面的 setUrl 方法实现浏览器 URL 的更新。

function setUrl(page){
    var url = location.pathname + '?page=' +  page
    history.pushState({url: url, title: document.title}, document.title, url)
}

history.pushState() 带有三个参数:一个状态对象,一个标题(现在被忽略了),以及一个可选的URL地址。

  • state object — 状态对象是一个由 pushState()方法创建的与历史纪录相关的JS对象。

  • title — 火狐浏览器现在已经忽略此参数,将来也许可能被使用。考虑到将来有可能的改变,传递一个空字符串是安全的做法。当然,你可以传递一个短标题给你要转变成的状态。

  • URL — 这个参数提供了新历史纪录的地址。请注意,浏览器在调用pushState()方法后不会去加载这个URL,但有可能在之后会这样做,比如用户重启浏览器之后。新的URL可以是绝对地址,也可以是相对地址。新URL必须和当前URL在同一个源下。

想看实现效果?参考这里一个无刷新分页的 DEMO ,建议看看源码实现。

作者:若愚

166 thoughts on “如何在不刷新页面的情况下改变URL”

  1. Pretty part of content. I simply stumbled upon your website and in accession capital to claim that I acquire in fact enjoyed account your weblog posts. Anyway I’ll be subscribing in your feeds and even I success you get entry to persistently fast.|

  2. I’m no longer certain the place you are getting your information, however good topic. I needs to spend some time studying more or figuring out more. Thanks for fantastic info I used to be looking for this info for my mission.|

  3. I have learn a few good stuff here. Certainly value bookmarking for revisiting. I surprise how a lot attempt you set to create this type of wonderful informative site.|

  4. I absolutely love your blog and find many of your post’s to be what precisely I’m looking for. Does one offer guest writers to write content available for you? I wouldn’t mind composing a post or elaborating on many of the subjects you write regarding here. Again, awesome website!|

  5. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your website? My website is in the exact same area of interest as yours and my visitors would genuinely benefit from some of the information you present here. Please let me know if this okay with you. Regards!|

  6. Its such as you learn my mind! You appear to grasp a lot about this, such as you wrote the e-book in it or something. I feel that you just could do with some to power the message home a bit, however instead of that, this is magnificent blog. A great read. I will definitely be back.|

  7. We are a group of volunteers and opening a new scheme in our community. Your website offered us with valuable info to work on. You have done an impressive job and our whole community will be thankful to you.|

  8. Hi there, You’ve done a great job. I’ll definitely digg it and personally recommend to my friends. I am sure they’ll be benefited from this site.|

  9. Excellent post. I used to be checking constantly this blog and I am inspired! Very useful info specially the remaining phase 🙂 I deal with such information a lot. I was seeking this certain info for a very lengthy time. Thanks and best of luck. |

  10. Simply want to say your article is as astonishing. The clearness for your post is just excellent and that i could think you are an expert on this subject. Fine along with your permission allow me to grab your feed to stay up to date with forthcoming post. Thank you one million and please keep up the rewarding work.|

  11. Fantastic blog you have here but I was curious about if you knew of any discussion boards that cover the same topics discussed in this article? I’d really like to be a part of online community where I can get feed-back from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Appreciate it!|

  12. I know this site gives quality depending posts and additional material, is there any other website which presents these information in quality?|

  13. I am not sure the place you are getting your info, however good topic. I must spend a while learning much more or understanding more. Thank you for excellent information I used to be in search of this information for my mission.|

  14. Thanks for your personal marvelous posting! I really enjoyed reading it, you might be a great author. I will ensure that I bookmark your blog and definitely will come back sometime soon. I want to encourage you to definitely continue your great work, have a nice afternoon!|

  15. Heya terrific blog! Does running a blog such as this require a lot of work? I have absolutely no understanding of computer programming but I had been hoping to start my own blog soon. Anyway, should you have any recommendations or techniques for new blog owners please share. I understand this is off subject however I simply had to ask. Thanks a lot!|

  16. you are in reality a excellent webmaster. The website loading velocity is amazing. It kind of feels that you are doing any unique trick. Moreover, The contents are masterwork. you have done a fantastic activity on this matter!|

  17. Does your site have a contact page? I’m having a tough time locating it but, I’d like to shoot you an email. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it develop over time.|

  18. Definitely believe that which you stated. Your favorite reason appeared to be on the net the easiest thing to be aware of. I say to you, I certainly get irked while people think about worries that they plainly don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks|

  19. Hello, Neat post. There is a problem with your web site in internet explorer, would test this? IE still is the market chief and a good element of other people will pass over your great writing due to this problem.|

  20. Heya just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.|

  21. It’s appropriate time to make a few plans for the long run and it is time to be happy. I’ve read this put up and if I could I want to recommend you few attention-grabbing things or tips. Maybe you can write next articles relating to this article. I wish to learn even more things about it!|

  22. Every weekend i used to visit this site, because i wish for enjoyment,
    for the reason that this this web page conations in fact pleasant funny information too.

  23. Simply want to say your article is as surprising. The clearness in your post is simply nice and i can assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.|

  24. Greetings from Colorado! I’m bored to tears at work so I decided to check out your site on my iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home. I’m amazed at how quick your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, good site!|

  25. Great post. I was checking constantly this weblog and I am impressed! Very helpful info specifically the ultimate phase 🙂 I care for such information a lot. I was looking for this particular information for a very long time. Thank you and best of luck. |

  26. It’s not my first time to pay a quick visit this website, i am visiting this web site dailly and take pleasant
    information from here daily.

  27. You actually make it seem really easy with your presentation however I in finding this topic to be actually something that I believe I’d by no means understand. It sort of feels too complicated and very wide for me. I am having a look forward in your next put up, I will attempt to get the hold of it!|

  28. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.|

  29. Someone necessarily lend a hand to make severely articles I’d state. That is the very first time I frequented your web page and thus far? I surprised with the analysis you made to create this actual publish amazing. Great activity!|

  30. Hello there! This post could not be written any better!
    Looking through this post reminds me of my previous roommate!
    He continually kept preaching about this. I’ll forward this post to him.

    Fairly certain he’ll have a good read. Many
    thanks for sharing!

  31. I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to create my own blog and would like to know where u got this from. appreciate it|

  32. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your
    point. You clearly know what youre talking about, why waste your intelligence on just posting
    videos to your blog when you could be giving us something informative to read?

  33. Hello there! I could have sworn I’ve been to this site before but after reading through some of the post I realized it’s new to me. Anyways, I’m definitely delighted I found it and I’ll be bookmarking and checking back frequently!|

  34. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.|

  35. Pretty great post. I just stumbled upon your weblog and wished to mention that I have really enjoyed surfing around your blog posts. After all I’ll be subscribing for your feed and I’m hoping you write once more very soon!|

  36. My brother suggested I may like this website. He used to be entirely right. This post actually made my day. You cann’t consider simply how a lot time I had spent for this info! Thank you!|

  37. Heya just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.|

  38. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.|

  39. This is very interesting, You are a very skilled blogger. I have joined your feed and look ahead to in quest of more of your wonderful post. Also, I have shared your web site in my social networks|

  40. Hey would you mind sharing which blog platform you’re working with? I’m looking to start my own blog in the near future but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Apologies for being off-topic but I had to ask!|

  41. I like what you guys are usually up too. This sort of clever work and coverage! Keep up the excellent works guys I’ve you guys to my own blogroll.|

  42. Hi there I am so grateful I found your weblog, I really found you by error, while I was looking on Bing for something else, Anyways I am here now and would just like to say cheers for a tremendous post and a all round exciting blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the awesome job.|

  43. Hey there this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!|

  44. I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to design my own blog and would like to find out where u got this from. appreciate it|

  45. Neat blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog jump out. Please let me know where you got your design. Bless you|

  46. This is really attention-grabbing, You’re an overly professional blogger. I have joined your rss feed and look ahead to seeking extra of your excellent post. Additionally, I have shared your web site in my social networks|

  47. I’ve been surfing on-line greater than three hours nowadays, but I never discovered any fascinating article like yours. It is pretty price sufficient for me. In my opinion, if all web owners and bloggers made just right content as you probably did, the internet will probably be a lot more useful than ever before.|

  48. Do you mind if I quote a few of your articles as long as I provide credit and sources back to your webpage? My blog is in the exact same area of interest as yours and my users would really benefit from a lot of the information you present here. Please let me know if this ok with you. Thanks a lot!|

  49. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is fundamental and all. However think of if you added some great images or videos to give your posts more, “pop”! Your content is excellent but with images and videos, this blog could undeniably be one of the most beneficial in its niche. Amazing blog!|

  50. Hello there! Would you mind if I share your blog with my zynga group? There’s a lot of people that I think would really appreciate your content. Please let me know. Thanks|

  51. Hi there! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.|

  52. Hello just wanted to give you a brief heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.|

  53. Good post. I learn something new and challenging on websites I stumbleupon every day. It will always be helpful to read content from other authors and use a little something from their web sites. |

  54. Whats up very nice web site!! Man .. Beautiful .. Superb .. I will bookmark your site and take the feeds additionally? I’m glad to search out so many useful info here in the put up, we need work out more strategies in this regard, thanks for sharing. . . . . .|

  55. The other day, while I was at work, my cousin stole my iPad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is totally off topic but I had to share it with someone!|

  56. Definitely believe that which you said. Your favorite reason seemed to be on the web the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks|

  57. Hi just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.|

  58. Heya are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding knowledge to make your own blog? Any help would be greatly appreciated!|

  59. I am really loving the theme/design of your website. Do you ever run into any browser compatibility problems? A small number of my blog readers have complained about my website not working correctly in Explorer but looks great in Chrome. Do you have any suggestions to help fix this issue?|

  60. I do agree with all of the concepts you’ve presented to your post. They’re very convincing and will certainly work. Still, the posts are very short for newbies. May you please lengthen them a little from subsequent time? Thanks for the post.|

  61. Attractive section of content. I just stumbled upon your website and in accession capital to say that I acquire in fact loved account your weblog posts. Any way I will be subscribing in your feeds or even I success you get admission to constantly fast.|

  62. It’s a pity you don’t have a donate button! I’d without a doubt donate to this brilliant blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will talk about this site with my Facebook group. Talk soon!|

  63. Hello, i think that i saw you visited my web site so i came to “return the favor”.I am trying to find things to enhance my website!I suppose its ok to use some of your ideas!!|

  64. You really make it seem so easy with your presentation however I to find this topic to be really one thing which I feel I’d by no means understand. It sort of feels too complicated and extremely vast for me. I’m having a look ahead in your next put up, I will try to get the hang of it!|

  65. Good day I am so delighted I found your webpage, I really found you by mistake, while I was researching on Bing for something else, Nonetheless I am here now and would just like to say cheers for a marvelous post and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the excellent jo.|

  66. I think this is among the most vital info for me. And i am glad reading your article. But should remark on few general things, The site style is perfect, the articles is really excellent : D. Good job, cheers|

  67. Thanks on your marvelous posting! I genuinely enjoyed reading it, you could be a great author. I will make sure to bookmark your blog and will often come back at some point. I want to encourage that you continue your great job, have a nice afternoon!|

  68. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your site? My blog is in the very same niche as yours and my users would really benefit from a lot of the information you provide here. Please let me know if this alright with you. Regards!|

  69. Hey there! I’ve been reading your blog for some time now and finally got the courage to go ahead and give you a shout out from Houston Texas! Just wanted to mention keep up the fantastic work!|

  70. Its such as you learn my thoughts! You appear to know a lot approximately this, such as you wrote the book in it or something. I feel that you can do with a few p.c. to power the message home a bit, but other than that, this is excellent blog. A fantastic read. I will certainly be back.|

  71. I’ve been surfing online more than three hours today, yet I never discovered any fascinating article like yours. It’s pretty price enough for me. In my view, if all webmasters and bloggers made just right content as you probably did, the internet might be much more helpful than ever before.|

  72. Hi there would you mind letting me know which web host you’re working with? I’ve loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot quicker then most. Can you suggest a good hosting provider at a fair price? Many thanks, I appreciate it!|

  73. Thanks, I’ve just been looking for info about this topic for a long time and yours is the best I’ve discovered so far. However, what concerning the bottom line? Are you positive concerning the supply?

  74. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.|

发表评论

电子邮件地址不会被公开。