CAutoComplete HowTo设置回叫功能? II - php

嗨,我正在使用SAutoComplete(扩展了CAutoComplete),当从列表中选择一个值时,需要做一些工作。

我正在这样使用它。

this->widget('application.components.SAutoComplete', array('width'=>200,
            'model'=>$cssAtapsClient, 'parseData'=>true, 'matchContains'=>true,
            'attribute'=>'suburb_id', 'data'=>$postCode, 'ddindicator'=>true,
            'max'=>50,
            'multipleSeparator'=>false,
            'options' => array(
            'select' => new CJavaScriptExpression('function(e, ui) { alert("hi"); }')
             ),
          )); ?>

我想知道为什么在自动完成的jquery UI中没有可用的选择选项?

选择示例如下。

$("#auto_cp").autocomplete({
    minLength: 3,
    //source
    source: function(req, add) {
        $.getJSON("friends.php?callback=?", req, function(data) {
            var suggestions = [];
            $.each(data, function(i, val) {
                suggestions.push({
                    label: val.name,
                    zzz: val.zzz
                });
            });
            add(suggestions);
        });
    },
    //select
    select: function(e, ui) {
        alert(ui.item.zzz);
    }
});​

编辑2

http://www.yiiframework.com/doc/api/1.1/CAutoComplete

代码是这样的,

<?php

class SAutoComplete extends CAutoComplete
{
   public $ddindicator;
   /**
    *
    * @var boolean whether to parse the data assumes data uses an assoc array
    *  array(value => array(name, value, ...), ...). Only works with a model present
    */
   public $parseData;
   /**
    * @var boolean whether to raise the change event
    */
   public $raiseChangeEvent = false;
   /**
    * Initializes the widget.
    * This method registers all needed client scripts and renders
    * the autocomplete input.
    */
   public function init()
   {
      if ( !$this->max )
         $this->max = 50000;

      if ( $this->ddindicator )
         $this->alternateInit();
      else
         parent::init();
   }

   public function alternateInit()
   {
      list($name,$id)=$this->resolveNameID();
      $this->htmlOptions['id'] = $id.'_input';
      $this->minChars = 0;

      echo CHtml::openTag('div', array('class'=>'ac-input-dd'));
      echo CHtml::openTag('div', array('class'=>'ac-input-btn'));
      echo CHtml::closeTag('div');

      if($this->hasModel())
      {
         $htmlOpt = array();

         if ( $this->parseData )
         {
            $menu = $this->data;
            $key = $this->attribute;

            //Change if attribute is apart of a array. eg attribute[0]
            $pos1 = stripos($key, '[');
            $pos2 = stripos($key, ']');
            if($pos1!==false && $pos2!==false)
            {
               $key = str_replace (substr($key,$pos1,$pos2 - $pos1 + 1),'',$key);
               $htmlOpt['value'] = isset($this->model->$key) ? $this->model->$key : '';
            }

            $this->value = isset($menu[$this->model->$key][0]) ? $menu[$this->model->$key][0] : '';
            $this->data = is_array($menu) ? array_values($menu) : array('Error in data.');
         }

         echo CHtml::activeHiddenField($this->model, $this->attribute, array_merge(array('id'=>$id, 'name'=>$name), $htmlOpt));
         echo CHtml::textField('', $this->value, $this->htmlOptions);
      }
      else
      {
         echo CHtml::hiddenField($name, $this->value, array('id'=>$id));
         echo CHtml::textField($name.'_input',$this->value,$this->htmlOptions);
      }
      echo CHtml::closeTag('div');

      $this->methodChain = $this->methodChain.'.result(function(evt, data, formatted) { $("#'.
              $id.'").val(data ? data[1] : "")'.($this->raiseChangeEvent?'.change()':'').'; })'.
              '.parent().find(".ac-input-btn").mousedown(function(){'.
              'jQuery(this).parent().find(".ac_input").toggleResults();})'.
              '.mouseup(function(){jQuery(this).parent().find(".ac_input").focus();});';

      $this->registerClientScript();
   }

   public static function registerScript()
   {
      $cs = Yii::app()->getClientScript();
      $cs->registerCoreScript('jquery');
      $cs->registerCoreScript('bgiframe');
        TK::registerScriptFile('autocomplete');
      $cs->registerCssFile($cs->getCoreScriptUrl().'/autocomplete/jquery.autocomplete.css');
   }

   /**
    * Registers the needed CSS and JavaScript.
    * @since 1.0.1
    */
   public function registerClientScript()
   {
      // can cut this down once YII releases a fix for defect #38
      if ( Yii::app()->request->isAjaxRequest || $this->ddindicator )
      {
         $id=$this->htmlOptions['id'];

         $acOptions=$this->getClientOptions();
         $options=$acOptions===array()?'{}' : CJavaScript::encode($acOptions);

         $cs=Yii::app()->getClientScript();

         if($this->data!==null)
            $data=CJavaScript::encode($this->data);
         else
         {
            $url=CHtml::normalizeUrl($this->url);
            $data='"'.$url.'"';
         }

         if ( Yii::app()->request->isAjaxRequest )
         {
            echo '<script type="text/javascript">jQuery(document).ready('.
                    'function() {jQuery("#'.$id.'").autocomplete('.$data.','.$options.')'.
                    $this->methodChain.';});</script>';
         }
         else
         {
            SAutoComplete::registerScript();
            $cs->registerScript('Yii.CAutoComplete#'.$id,"jQuery(\"#{$id}\").autocomplete($data,{$options}){$this->methodChain};");
         }
      }
      else
         parent::registerClientScript();
   }
}

参考方案

尝试添加这个,

'methodChain'=>".result(function(event,item){ urFunction(); })",

祝你今天愉快!

所以最后看起来像

$this->widget('application.components.SAutoComplete', array('width'=>200,
            'model'=>$cssAtapsClient, 'parseData'=>true, 'matchContains'=>true,
            'attribute'=>'suburb_id', 'data'=>$postCode, 'ddindicator'=>true,
            'max'=>50,
            'methodChain'=>".result(function(event,item){ urFucntion(); })",
         ));

PHP:对数组排序 - php

请如何排序以下数组Array ( 'ben' => 1.0, 'ken' => 2.0, 'sam' => 1.5 ) 至Array ( 'ken' => 2.0, 'sam' => 1.5, 'ben' =&…

PHP PDO组按列名称查询结果 - php

以下PDO查询返回以下结果:$db = new PDO('....'); $sth = $db->prepare('SELECT ...'); 结果如下: name curso ABC stack CDE stack FGH stack IJK stack LMN overflow OPQ overflow RS…

PHP Array重复数据计数 - php

我在PHP Array中有标题和语言数据。我需要显示重复的标题计数。请检查以下数组格式。Array ( [0] => Array ( [title] => My_title1 [language] => English ) [1] => Array ( [title] => My_title1 [language] => …

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…