我有一个只有一个字段的表单,na input type = "text"
当表单提交时,URL如下所示:
http://localhost:8765/products/search?search=notebook
我希望它在接受表单时以以下方式出现:
http://localhost:8765/products/search/notebook
手动键入URL效果非常好(我创建了一个方法,可以在搜索,还创建了一个路由,指定上面有一个URL(。
路线代码(routes.php(:
$routes->connect('/products/search/:search', ['controller' => 'Products', 'action' => 'search'],
[':search' => ''w+', 'pass' => ['search']]);
ProductsController.php代码(负责操作搜索的方法(
public function search($search)
{
if($this->request->is('get'))
{
//$product = $this->request->params['pass'];
$this->paginate = [
'fields' => ['product_name', 'quantity', 'sold', 'description', 'price', 'old_price', 'thumbnail'],
'conditions' => ['product_name LIKE' => '%'.$search.'%'],
'order' => ['price' => 'DESC'],
'limit' => 3
];
$this->set('products', $this->paginate($this->Products));
}
}
表单代码:
<?= $this->Form->create(null, ['url' => ['controller' => 'Products', 'action' => 'search'], 'type' => 'get', 'id' => 'search-form', 'class' => 'navbar-form span7 text-center']) ?>
<button class="btn btn-info" title="Favorite o Site">
<span class="glyphicon glyphicon-star"></span>
</button>
<?= $this->Form->text('search', ['class' => 'form-control', 'placeholder' => 'Search']) ?>
<?= $this->Form->button('Buscar <span class="glyphicon glyphicon-search"></span>', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
<?= $this->Form->end() ?>
OBS1:我认为应该在这个form
中进行更改(只是猜测(。
有两个基本解决方案
使用Js
您可以使用js更改表单提交到的url:
<form
method="GET"
action="/base/url/"
onsubmit="document.location=this.action+document.getElementById('search-input-id').value; return false;"
>
<input id="search-input" />
</form>
这非常简单,并且没有服务器端逻辑。
使用后重定向获取
或者,通过post提交表单,并将用户重定向到适当的url以查看结果(一种称为PRG的模式(。
例如:
<form method="POST">
<input name="search-input" id="search-input" />
</form>
通过适当的控制器操作:
public function search($search = null)
{
if($this->request->is('post')) {
$term = $this->request->data['search-item'];
// Any verification/validation/logic required
// Redirect to same controller action with this search term
return $this->redirect([$term]);
}
...
// GET request, with $search term
这种技术的优点是,在将用户发送到结果页面url之前,可以控制/验证/验证搜索项是否有效。
当提交form
时,我使用jQuery
库来抑制默认行为,创建一个新的url并进行重定向:
$("#search-form").submit(function(event){
event.preventDefault(); // suppress default behavior
action = $(this).attr('action') + '/' + document.getElementById('search').value; // create a new urldesejado
window.location.href = action; //make the redirection
});