最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sammy.js read route with &,? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Jun 25, 2017 at 15:08 laser 1,37613 silver badges14 bronze badges asked Apr 4, 2014 at 3:52 nelly2knelly2k 8111 gold badge11 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论