我在 CakePHP 2.0 中实现 JQuery UI 自动完成时遇到了麻烦。想要在 Grocery 列表视图上显示项目列表,以允许用户选择数据库中已有的项目,而不是创建新项目。
应用程序jQuery:
////file:app/webroot/js/application.js
$(document).ready(function(){
// Caching the Item textbox:
var item = $('#item');
// Defining a placeholder text:
item.defaultText('Search for items');
// Using jQuery UI's autocomplete widget:
item.autocomplete({
minLength: 1,
source: 'http://localhost/groceries/groclists/search'
////**part of the problem was here, needs to be full source**
});
});
// 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();
}
视图中的项目形式:
<div class="items form">
<?php echo $this->Form->create('Item', array('action' => 'search')); ?>
<?php echo $this->Form->input('item', array('type' => 'text', 'id' => 'item', 'label' => 'Search')); ?>
<?php echo $this->Form->end(__('Submit', true)); ?>
</div>
项目控制器搜索():
public function search() {
if ($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
$this->autoRender = false;
$query = $_GET['term'];
$searchitems = $this->Item->find('all', array(
'conditions' => array('Item.name LIKE' => '%' . $query . '%')));
$i = 0;
foreach ($searchitems as $searchitem) {
$response[$i]['value'] = $searchitem['Item']['name'];
$response[$i]['label'] = $searchitem['Item']['id'];
$i++;
}
echo json_encode($response);
} else {
if (!empty($this->data)) {
$this->set('items', $this->paginate(array('Item.name LIKE' => '%' . $this->data['Item']['name'] . '%')));
}
}
}
我很茫然,欢迎任何输入。
在对 Application.js 进行上述更改后,我现在收到了对我网页的响应。根据目前数据库中包含的内容,它具有正确数量的结果,但它是一个空响应。来自 Firebug 的响应如下:
[{"value":null,"label":null},{"value":null,"label":null},{"value":null,"label":null},{"value":null,"label":null}]
这是我的响应标头:
Response Headers
Date Sun, 18 Sep 2011 14:48:37 GMT
Server Apache/2.2.11 (Win32) PHP/5.3.0
X-Powered-By PHP/5.3.0
Content-Length 113
Keep-Alive timeout=5, max=100
Connection Keep-Alive
Content-Type text/html; charset=UTF-8
Request Headers
Host localhost
User-Agent Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost/groceries/groclists/view/3
Cookie CAKEPHP=hu7ksthrlfms0lqod3rdq296f5