在投资组合控制器中的行动 ajax_clients_dropdown 放这个
public function ajax_clients_dropdown($model="portfolio") {
$this->loadModel($model); // loadmodel let me use this action for multiple model
$this->$model->recursive = -1;
$this->autoRender = false;
$this->layout = 'ajax';
if ($this->request->is('ajax')) {
$results = $this->$model->find('all', array('fields' => array('id','name'),
'conditions' => array('name LIKE ' => '%'. $this->request->query['q'] . '%'),
));
$return_arr= array();
// you can change this loop with this
// $res = Hash::extract($results, '{n}.source'); // and change in your find condition 'name' with "name as label' cause in our script we will use the term "label"
foreach ($results as $row) {
$row_array['id'] = $row['source']['id'];
$row_array['label'] = $row['source']['name'];
array_push($return_arr,$row_array);
}
// echo json_encode($return_arr); WRONG!!!
// THE TRICK IS HERE => add before your json the callback send by jquery and it will work!!!!
$response = $this->request->query["callback"] . "(" . json_encode($return_arr) . ")";
echo $response;
}
}
在 /Layout/ajax.ctp 中放这段代码
<?php echo $this->fetch('content'); ?>
在你的默认布局之间,记得加载jquery和jqueryui
...
<?php
echo $this->Html->script('jquery-1.11.1');
echo $this->Html->script('jquery-migrate-1.2.1');
echo $this->Html->script('jquery-ui/jquery-ui-1.10.4.min');
?>
...
在你看来 View/Portofolio/yourview.ctp 尝试做这样的事情
<input id="tags" placeholder="your placeholder . bla bla bla">
</div>
<hr>
<input id="source_dest_id" type="hidden" name="source_dest_id" value=""/>
<script>
$(function(){
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "<?php echo $this->webroot;?>portfolios/ajax_clients_dropdown",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
},
focus: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// manually update the textbox
$(this).val(ui.item.label);
},
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// manually update the textbox and hidden field
$(this).val(ui.item.label);
$("#source_dest_id").val(ui.item.id);
}
});
});
</script>
希望对你有所帮助:)