我有一个包含单个字段的表单,在提交表单时为input type = "text"
,网址如下:
http://localhost:8765/products/search?search=notebook
我希望它在接受表格时以下列方式起作用:
http://localhost:8765/products/search/notebook
手动输入 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
进行更改(只是一个猜测)。
答案 0 :(得分:4)
有两种基本解决方案
您可以使用js更改表单提交的网址:
<form
method="GET"
action="/base/url/"
onsubmit="document.location=this.action+document.getElementById('search-input-id').value; return false;"
>
<input id="search-input" />
</form>
这很简单,没有服务器端逻辑。
或者,通过邮寄提交表单,并将用户重定向到相应的网址以查看结果(称为PRG的模式)。
E.g:
<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
此技术的优势在于,在将用户发送到结果页面网址之前,有一种控制/验证/验证搜索字词有效的方法。
答案 1 :(得分:2)
我使用jQuery
lib来提交form
时抑制默认行为,创建一个新网址并进行重定向:
$("#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
});