我正在尝试使用 jquery UI 进行自动完成。它的工作原理是当用户在搜索框中输入信息时,会进行 ajax 调用。然后服务器返回 json 结构的 html。这是我的代码。我是根据我在网上找到的教程得到的
服务器端代码
public function user_lookup() {
if($this->request->is('ajax')) {
$this->autoRender=false;
$users=$this->User->find('all',array('conditions'=>array('User.username LIKE'=>'%'.$_GET['term'].'%')));
$i=0;
foreach($users as $user){
$response[$i]['value']=$user['User']['username'];
$response[$i]['label']="<img class='avatar' width='24' height='24' src=''/>
<span class='username'>".$user['User']['username']."</span>";
$i++;
}
echo json_encode($response);
}
}
jQuery代码
$(document).ready(function() {
// Caching the movieName textbox:
var username = $('#SearchUsername');
// Defining a placeholder text:
username.defaultText('Search for people');
// Using jQuery UI's autocomplete widget:
username.autocomplete({
minLength : 1,
source : URLSITESUFFIX+'/users/user_lookup'
});
});
// A custom jQuery method for placeholder text:
$.fn.defaultText = function(value){
var element = this.eq(0);
element.data('defaultText',value);
element.focus(function(){
if(element.val() == value){
element.val('').removeClass('defaultText');
}
}).blur(function(){
if(element.val() == '' || element.val() == value){
element.addClass('defaultText').val(value);
}
});
return element.blur();
};
和 html
<?php echo $this->Form->create('ProjectsUser'); ?>
<?php echo $this->Form->input('Search.username'); ?>
<?php echo $this->Form->end();?>
但结果返回文字文本而不是呈现 html。我添加了一个截屏视频 http://screencast.com/t/OhgPHpTWVe