我的应用程序基本上采用某种形式输入并返回一组结果。我有两条路线
routes: {
'': 'search',
'search': 'search',
'results/:query': 'results'
},
results: function(query) {
var search = new ResultsSearchView();
var grid = new GridView({ query: query });
}
如果查询包含任何字符/特别是(在这种情况下可能完全发生),它们将被添加到 URL 中,我的路由会中断。
我试过使用
encodeURI()
和 encodeURIComponent()
有点我没有任何运气。你们这些人是怎么处理的?
最佳答案
您可以使用 encodeURIComponent
构建 URL 以转换 /
时至 %2F
然后 decodeURIComponent
在路由处理程序内部将它们转换回来; HTML 将看起来像这样:
<a href="#results/pancakes">no slash</a>
<a href="#results/where%2Fis%2Fpancakes%2Fhouse">with slashes</a>
然后在路由器中:
routes: {
'results/:query': 'results'
},
results: function(query) {
query = decodeURIComponent(query);
// Do useful things here...
}
演示:http://jsfiddle.net/ambiguous/sbpfD/
或者,您可以使用 splat route :
Routes can contain parameter parts,
:param
, which match a single URL component between slashes; and splat parts*splat
, which can match any number of URL components.
所以你的 HTML 应该是这样的:
<a href="#results/pancakes">no slash</a>
<a href="#results/where/is/pancakes/house">with slashes</a>
和你的路由器:
routes: {
'results/*query': 'results'
},
results: function(query) {
// Do useful things here...
}
演示:http://jsfiddle.net/ambiguous/awJxG/
关于当查询传递给路由时,backbone.js 路由包含/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13753180/