我正在尝试在CakePHP中创建一个自动完成功能,但没有成功。我尝试了以下代码。
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
//表单和jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
答案 0 :(得分:2)
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
打破你的JSON结构。
请注意,默认情况下自动填充需要&#34;标签&#34; JSON表中的值和值键,因此在获取DB记录后,所有脚本都应该执行:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
另外,我将通过
在jQuery设置中创建数据源的URLsource:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
尝试注释掉(只是为了确保在自动完成功能调用时请求是否满足条件)
if ($this->request->is('ajax')) {
条件