backbone.js routing when query passed to route contains /

走远了吗. 提交于 2019-12-23 09:57:41

问题


My app basically takes some form input and returns a set of results. I have two routes

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

If the query contains any characters / specifically (can totally happen in this case), they are added to the URL and my route breaks.

I have tried using encodeURI() and encodeURIComponent() bit I'm not having any luck. How are you folks handling such things?


回答1:


You can use encodeURIComponent when building the URL to convert the / to %2F and then decodeURIComponent inside the route handler to convert them back; the HTML would end looking like this:

<a href="#results/pancakes">no slash</a>
<a href="#results/where%2Fis%2Fpancakes%2Fhouse">with slashes</a>

and then in the router:

routes: {
    'results/:query': 'results'
},
results: function(query) {
    query = decodeURIComponent(query);
    // Do useful things here...
}

Demo: http://jsfiddle.net/ambiguous/sbpfD/

Alternatively, you could use a 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.

So your HTML would be like this:

<a href="#results/pancakes">no slash</a>
<a href="#results/where/is/pancakes/house">with slashes</a>

and your router:

routes: {
    'results/*query': 'results'
},
results: function(query) {
    // Do useful things here...
}

Demo: http://jsfiddle.net/ambiguous/awJxG/



来源:https://stackoverflow.com/questions/13753180/backbone-js-routing-when-query-passed-to-route-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!