如果你正在做一個搜索頁面,我建議傳球參數使用GET而不是POST。用戶通常會將搜索添加爲書籤,如果使用POST完成搜索,則無法保留結果。
這是一個(快速入侵)如何做自動完成的例子。
你的搜索視圖
<form method="get" action="/controller/search">
<?php echo $this->Form->input('Search.searchby', array('type' => 'select', 'options' => $searchByList, 'label' => 'Search By:'));?>
<?php echo $ajax->autoComplete('Search.searchvalue', '/controller/autoComplete/', array('minChars' => 2)); ?>
<input name="search" type="submit" value="Search"/>
</form>
它需要一個名爲「控制器」控制器,它使用兩個功能(「搜索」和「自動完成」)
function search() {
// GET parameters for search
$searchby = (isset($this->params['url']['searchby'])) ? ($this->params['url']['searchby']) : '';
$searchvalue = (isset($this->params['url']['searchvalue'])) ? ($this->params['url']['searchvalue']) : '';
// DO SEARCH HERE
$conditions = array('searchby'=>$searchby, 'searchvalue' => $searchvalue);
…etc…
}
function autocomplete() {
if(!empty($this->data['Search']['searchvalue'])){
$rs = $this->Search->findAll(array('searchvalue' => "LIKE {$this->data['Search']['searchvalue']}%"));
$this->set('searchvalues', $rs);
}
$this->render('autocomplete', 'ajax');
}
自動完成AJAX部件需要一個視圖模板命名爲'autocomplete.ctp'
<!-- autocomplete.ctp -->
<ul>
<?php if(isset($searchvalues) && !empty($searchvalues)){ ?>
<?php foreach($searchvalues as $t) { ?>
<li><?php echo $t['Search']['searchvalue']; ?></li>
<?php } ?>
<?php } ?>
</ul>
這應該讓你指出正確的方向ñ。如果你想得到select標籤的值並通過ajax傳遞它,那麼你應該看看ajax函數用於序列化表單,你可能必須手工編寫javascript代碼,知道如果AJAX助手有序列化形式的選擇。這裏的一些代碼我用來序列只是一個選擇標籤。可能是有益的)
<?php
$graph_type = array(
'impressions'=>'Impressions',
'click_throughs'=>'Click Throughs',
'click_through_ratio'=>'Click Through Ratio',
'time_with_brand'=>'Time with Brand',
'average_time_with_brand'=>'Average Time with Brand'
);
echo $html->selectTag('Graph/type', $graph_type, null, array('onChange' => 'event.returnValue = false; return false;', 'style' => 'margin-right:20px;'),null, false);
echo $javascript->event("'GraphType'", "change",
$ajax->remoteFunction(
array(
'update' => 'graph_container',
'url' => '/reports/ajax_graph_multiple',
'with'=>"Form.serialize('reports_form')"
)
)
);
?>
感謝了很多,但我的問題是關於我如何在searchBy傳中自動完成()函數自動完成(){ 如果(!空($這個 - >數據[ '搜索'] [ 'searchvalue' ])){ $ rs = $ this-> Search-> findAll(array('searchvalue'=>「LIKE {$ this-> data ['Search'] ['searchvalue']}%」)); $ this-> set('searchvalues',$ rs); } $ this-> render('autocomplete','ajax'); } – caker 2011-03-16 14:52:51
謝謝大家。我通過切換到jquery來解決它! – caker 2011-03-17 14:39:06