Javascript 包括根主干路由
我注意到我正在构建的主干应用程序中有一个小小的怪癖,我想知道这种行为是否是预期的,或者我是否做错了什么 我点燃了脊梁骨。历史就是这样:Javascript 包括根主干路由,javascript,ajax,backbone.js,router,Javascript,Ajax,Backbone.js,Router,我注意到我正在构建的主干应用程序中有一个小小的怪癖,我想知道这种行为是否是预期的,或者我是否做错了什么 我点燃了脊梁骨。历史就是这样: Backbone.history.start({ root: '/au/store/', pushState: true, silent: true }); 要创建后退/前进按钮导航触发路线,我需要如下设置: router = Backbone.Router.extend({ routes: { 'au/store/:slug' : '
Backbone.history.start({
root: '/au/store/',
pushState: true,
silent: true
});
要创建后退/前进按钮导航触发路线,我需要如下设置:
router = Backbone.Router.extend({
routes: {
'au/store/:slug' : 'slug',
'au/store/?*params' : 'params'
}
});
这个很好用。在浏览器历史记录中导航到/au/store/?foo=bar
会按预期触发“params”路由
但我遇到的问题是router.navigate()
不会触发路由:
router.navigate('?foo=bar', {trigger:true}); // route doesn't trigger
将根目录添加到url也不起作用:
router.navigate('au/store/?foo=bar', {trigger:true}); // navigates to /au/store/au/store/?foo=bar
因此,我目前使用的解决方法是运行所有路由两次,一次带根前缀,一次不带根前缀:
routes: {
'au/store/:slug' : 'slug',
'au/store/?*params' : 'params',
':slug' : 'slug',
'?*params' : 'params'
}
现在,它会在后退/前进以及通过router.navigate()触发路由
但这看起来有点像黑客,肯定会在更复杂的路线上造成问题
有人能解释一下我做错了什么,或者为什么它没有按照我的预期运行吗?去掉完整的URL,主干会自动为您预先设置根。那么,就说:
routes: {
':slug' : 'slug',
'?*params' : 'params'
}
你应该没事。去掉路由器中的URL
router = Backbone.Router.extend({
routes: {
':slug' : 'slug',
'?*params' : 'params'
}
});
将silent
设置为false
以触发路由
Backbone.history.start({
root: '/au/store/',
pushState: true,
silent: false
});
如果服务器已经呈现了整个页面,并且您不希望在启动历史记录时触发初始路由,请传递silent:true
参考文献
更新
您还应该使用.htaccess来处理根目录和重定向。您需要使用以下内容:
# html5 pushstate (history) support:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteBase /au/store/
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ /au/store/$1 [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule (.*) index.php
</ifModule>
html5 pushstate(历史)支持:
重新启动发动机
更新基地/区域/商店/
RewriteCond%{THE_REQUEST}^.*/index.php
重写规则^(.*)index.php$/au/store/$1[R,L]
重写cond%{REQUEST_FILENAME}-F
重写cond%{REQUEST_FILENAME}-D
重写cond%{REQUEST_URI}^/索引\.php
重写规则(.*)index.php
把这个加到你的头上
<base href="/au/store/" />
现在,先生,您得到了一个完美的工作环境当通过
路由器触发路由时,这可以正常工作。导航()
,但当使用后退/前进按钮导航时,无法识别路由。^如果我设置*参数
路由,它会将整个au/store/params
传递到回调…问题仍然存在。除非有根在其中的路由,否则浏览器后退/前进时不会触发正确的路由。因此,主干网0.9.2中对此进行了修复,它现在可以正常工作(如本问题的两个答案中所述)