简体   繁体   English

浏览器后退按钮更改动态URL参数

[英]Browser Back button changes dynamic url Parameters

I am working on a website, where url parameter gets updated based on user action, according to which I update the webpage without refreshing. 我正在一个网站上工作,其中url参数根据用户操作进行更新,根据该网站我更新网页而不刷新。 Consider the scenario of E-commerce where url changes when user clicks on filters and then updated products gets displayed. 考虑电子商务的场景,当用户点击过滤器然后显示更新的产品时,网址会发生变化。

Now the problem is, when user clicks on Browsers's back button the browser goes back to previous url-parameter, but page did not gets changed. 现在的问题是,当用户点击浏览器的后退按钮时,浏览器会返回上一个url-parameter,但页面没有被更改。 I want to change the page also based on url parameter that gets changed after back button clicked. 我想根据点击后退按钮后更改的url参数更改页面。

I have tried this solution: 我试过这个解决方案:

$($window).on('popstate', function (e) {
     // Update the page also
});

The problem with this code is, this gets fired as url changes, means it does not care about if browser back button is clicked, or url is changing using the jQuery. 这段代码的问题是,当url发生更改时会触发此问题,这意味着它不关心是否单击了浏览器后退按钮,或者是否使用jQuery更改了url。 So if I am changing url based on user interaction, the popstate callback will be called and my custom function also. 因此,如果我根据用户交互更改URL,则将调用popstate回调并调用我的自定义函数。 To update the page I am using https requests, so http api gets called two times. 要更新页面,我使用的是https请求,因此http api会被调用两次。

Is there any way to check if only "Back button" is clicked? 有没有办法检查是否只点击了“后退按钮”?

I would recommend you to change your design a litle bit and trigger all content updates (the product list in your case) by listening to url changes, not only url changes caused by the back button. 我建议您通过监听网址更改来更改您的设计并触发所有内容更新(在您的情况下为产品列表),而不仅仅是后退按钮引起的网址更改。 So instead of triggering any re-rendering on click events, let these buttons be regular link to the url that represent your content and trigger the functionality from the popstate event. 因此,不要触发对点击事件的任何重新呈现,而是让这些按钮定期链接到代表您的内容的URL并从popstate事件触发功能。

This is how all MVVM-frameworks like Angular.js, Backbone etc are designed and meant to be used. 这就是所有MVVM框架(如Angular.js,Backbone等)的设计和使用方式。

By doing this it will also be so much easier for you to maintain the application in the long run. 通过这样做,您可以更容易地长期维护应用程序。

Good luck! 祝好运!

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

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