Sammy.js read route with &,?

2019-05-15 11:51发布

Need to be route looks like

#/routeName/?param1=aaaa&param2=bbb

added to sammy

#/routeName/:param1/:param2

and

#/routeName/?:param1&:param2

none of them works

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-15 12:44

I've been looking into query parameters myself in Sammy.js, and discovered that (although it isn't mentioned in the API docs), Sammy does support query parameters. It simply adds any query parameters that it finds in your route to the route's Sammy.EventContext.params array. If you have a route structured like this:

Sammy(function() {
    this.get("#/routeName/", function(context) {
        alert("{'param1': '" + context.params.param1 + "', 'param2': '" + context.params.param2 + "'}");
    });
});

You'll find that, if you go to route "#/routeName/" you'll get "{'param1': undefined, 'param2': undefined}", but if you go to "#/routeName/?param1=aaaa&param2=bbb", you'll get "{'param1': 'aaaa', 'param2': 'bbb'}". This allows you to handle optional parameters in a way that is familiar to many REST API developers.


As for why your other two routes don't work:

#/routeName/:param1/:param2

has named, required parameters, which requires at least one non-/ (forward slash) character in order to match the route. At a minimum, you'd have to go to a route along the lines of "#/runRoute/a/b" in order to trigger that route from running. You wouldn't easily be able to get the effect you wanted without providing regular expressions in place of named parameters.

#/routeName/?:param1&:param2

has the trailing / after #/routeName/ being optional due to '?' being a special character in Sammy routes that signifies the previous character or expression (which can be defined using parenthesis) is optional. You'd potentially match '#/routeName&b' as well as #/routeName/e&b' using this route, with param1 being set to 'e' in both cases and param2 being set to 'b' in both cases. Due to the query parameter rules in place within Sammy, you would not easily be able to define a '?' within a route, but you could use the URL escaped form, '%3F'.


Hopefully this answers your question, I saw this question and had been working on similar issues recently. I won't claim to be the most knowledgeable person on Sammy, but we use it at my current job and this is what we've been able to figure out about it so far.

查看更多
登录 后发表回答