我正在CakePhp3.6中开发一个网站 我的header.ctp中有一个搜索表单。
<form id="frm-search" method="post" action="search">
<input type="hidden" name="_csrfToken" value="<?=$this->request->getParam('_csrfToken')?>" />
<input type="text" id="search-inp" name="search-inp" placeholder="Search by product name" />
<input type="submit" class="btn" />
</form>
在发布表单时,我会在我的route.php中提交以下路线:
$routes->connect('/search', ['controller' => 'Products', 'action' => 'searchProducts', 'search']);
我的控制器代码如下:
public function searchProducts(){
$products = null;
/*1. Get the search string as post param*/
$searchStr = (isset($_POST['search-inp']) ?$_POST['search-inp'] :"");
if (empty($searchStr))
echo json_encode($products);
/*2. remove the prepositions from the searchstr*/
$remStrArr = array('in', 'at', 'or', 'and', 'of', 'for');
foreach ($remStrArr as $str){
$searchStr = str_replace($str, "", $searchStr);
}
$searchStr = preg_replace('/\s+/', '/', $searchStr);
/*3. break the searchstr to terms in a array*/
$searchTermsArr = explode("/",$searchStr);
if(empty($searchTermsArr))
return json_encode($products);
/*4. search each term*/
foreach ($searchTermsArr as $term){
if(empty($products) || is_null($products)){
$products = array($this->searchByProdName($term));
}else{
array_push($products, $this->searchByProdName($term));
}
}
$products = $products[0];
$this->set(compact('products'));
}
在我的模板文件search_products.ctp中,显示搜索结果。
我的搜索工作文件,但问题是当我刷新搜索结果页面时,它要求重新提交数据。
为什么要求重新提交数据,我该如何阻止它?
谢谢