这是具有 GET 方法的 HTML 表单的默认行为。您需要自己构建该 URL。
后端方式
- 缺点:它向服务器发出两个请求,而不是一个
- 优点:更易于维护,因为 URL 是使用路由服务构建的
你的路由文件
_search:
pattern: /page/{category}/{keyword}
defaults: { _controller: Bundle:Default:page, category: 9, keyword: null }
_search_endpoint:
pattern: /page
defaults: { _controller: Bundle:Default:redirect }
你的控制器
public function redirectAction()
{
$category = $this->get('request')->query->get('category');
$keyword = $this->get('request')->query->get('keyword');
// You probably want to add some extra check here and there
// do avoid any kind of side effects or bugs.
$url = $this->generateUrl('_search', array(
'category' => $category,
'keyword' => $keyword,
));
return $this->redirect($url);
}
前端方式
使用 Javascript,您可以自己构建 URL,然后重定向用户。
- 缺点:您无权访问路由服务(尽管您可以使用FOSJsRoutingBundle 捆绑包 https://github.com/FriendsOfSymfony/FOSJsRoutingBundle)
- 优点:您可以节省一个请求
注意:您需要获取自己的查询字符串 getter,您可以找到Stackoverflow 线程在这里 https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript,下面我将使用getQueryString
在 jQuery 对象上。
(function (window, $) {
$('#theFormId').submit(function (event) {
var category, keyword;
event.preventDefault();
// You will want to put some tests here to make
// sure the code behaves the way you are expecting
category = $.getQueryString('category');
keyword = $.getQueryString('keyword');
window.location.href = '/page/' + category + '/' + keyword;
}):
})(window, jQuery);