2012-12-06 58 views
5

我的應用程序基本上需要一些表單輸入並返回一組結果。我有兩個途徑backbone.js路由查詢傳遞到路由時包含/

routes: { 
     '': 'search', 
     'search': 'search', 
     'results/:query': 'results' 
    }, 
    results: function(query) { 
     var search = new ResultsSearchView(); 
     var grid = new GridView({ query: query }); 
    } 

如果查詢中包含的任何字符/專(完全可以在這種情況下發生的),它們被添加到URL和我的路線休息。

我試過使用encodeURI()encodeURIComponent()位我沒有任何運氣。你們怎麼處理這些事情?

回答

4

構建URL時,您可以使用encodeURIComponent/轉換爲%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

路線可以包含參數部分,即:param,它們匹配單個URL組件削減和splat部分*splat,它可以匹配任意數量的URL組件。

所以,你的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/

+0

使用圖示路線,它的工作太棒了。感謝您的幫助。 – Charles