在Cakephp 2.0中使用JQuery UI自动完成

时间:2011-09-17 12:06:46

标签: jquery-ui cakephp jquery-ui-autocomplete cakephp-2.0

我在CakePHP 2.0中实现JQuery UI Autocomplete时遇到了麻烦。想要在杂货列表视图中显示项目列表,以允许用户选择数据库中已有的项目而不是创建新项目。

应用程序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

1 个答案:

答案 0 :(得分:0)

我不是特别清楚你在问什么,但这是我在CakePHP 1.2和1.3中用过的Javascript:

$.ajax({
  url: '/api/v1/zip_codes/utilities/' + zip + '/' + type + '.json',
  type: 'GET',
  dataType: 'json',
  success: function( data, status ) {
    var utility_type = data.Type.name;

    var $provider_name = $('#Building' + utility_type + 'ProviderName');
    var $provider_id   = $('#Building' + utility_type + 'ProviderId');

    // Massage the Cake data into something autocomplete-friendly
    var $friendly = $.map( data.Utilities, function( util ) {
    return { label: util.Utility.name, value: util.Utility.id };
  });

  // If more than one, populate the provider autocomplete options
  $provider_name.autocomplete({
    source: $friendly, // use the autocomplete-friendly data
    minLength: 0,
    focus: function( event, ui ) {
      $provider_name.val( ui.item.label );
      return false;
    },
    select: function( event, ui ) {
      $provider_name.val( ui.item.label );
      $provider_id.val( ui.item.value );
      return false;
    }
  }).data( 'autocomplete' )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
      .data( "item.autocomplete", item )
      .append( '<a>' + item.label + '</a>' )
      .appendTo( ul );
  };
});

此代码段检索以给定邮政编码操作的公用事业公司的名称和ID(仅提供一些上下文)。有关详细信息,a question I asked about this same issue可能有所帮助。