我正在尝试使用jquery自动完成库自动完成部门。 ajax调用如下
$( "#auto_complete" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/employees/getDepartment"
dataType: "jsonp",
//dataType: "text/html",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
alert("success--");
response( $.map( data.geonames, function( item ) {
return {
label: item.name,
value: item.id
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
我的控制器有一个名为getDepartment的动作如下:
public function getDepartment() {
$this->log($this->params->query['name_startsWith'] , 'debug');
$str = $this->params->query['name_startsWith'];
$this->log($str, 'debug');
$name='Departmet';
$this->layout = 'ajax';
$departments = $this->Employee->Department->find('all', array( 'recursive' => -1,
'conditions'=>array('Department.name LIKE'=>$str.'%'),
'fields'=>array('name', 'id')));
$this->set('departments',$departments);
}
这里我需要将$ departments作为Json发送。
当我运行时,我得到响应(使用fireBug)
[{"Department":{"name":"Testing","id":"1"}},{"Department":{"name":"Testing","id":"3"}},{"Department":{"name":"Testing2","id":"6"}},{"Department":{"name":"testing","id":"7"}},{"Department":{"name":"test","id":"8"}}]
答案 0 :(得分:1)
您的回复是有效的JSON,因此您的dataType
也必须是。
dataType: "json"