Select2:如何在init上进行xhr调用

时间:2014-12-23 17:49:50

标签: ajax select extjs yii initialization

我在Select2中对onChange事件进行了一些ajax调用。但是,当初始化/打开Select2时,我需要进行类似的调用。 怎么做?

$this->widget('ext.select2.ESelect2', array(
            'model'=> $model,
            'attribute'=> 'PaymentType',//'open'=>'js:{alert("init");}',
            'data' => CHtml::listData(PaymentMethod::model()->findall(), 'id','name'),
            'htmlOptions'=>array( 
                //'onInit'=>'js:{alert("init");}', // this does not work!!
                'onChange'=>CHtml::ajax(array('type'=>'GET',
                'url'=>$this->createUrl('user/cashlessUser', array ('id'=>Yii::app()->user->id)),
                'data'=>'js:{PaymentMethod: this.value }',
                'success'=>"js:function(data){   alert(data);   }",
                )),
            ), 
            'options'=> array('allowClear'=>true, 
                'width' => '250', 
                'placeholder' => '', 
                ),          
        ));  

更新

我在事件here上找到了eSelect2规范 但它适用于纯js,而我需要为Yii插件执行此操作,其中事件(onChange除外)未正确触发:

'htmlOptions'=>array(            
                'select2-opening'=> 'js: console.log("smth"); ',
                'select2-opening'=> ' console.log("smth"); ',
                'select2-opening'=> ' alert("smth"); ',
                's2id_Events_PaymentType.open'=> 'js: console.log("open"); ',
                'onFocus'=> 'js: console.log("smth"); ',
                'onOpen'=> 'js: console.log("smth"); ',  

s2id_Events_PaymentType是此特定电子选择的ID。

所有这些都没有被解雇,但没有发现任何错误。

更新2

我试图通过脚本绑定逻辑,但无济于事:

Yii::app()->clientScript->registerScript('some-script', "
    jQuery('#s2id_Events_PaymentType').on('select2-open', function(e) { console.log('open'); });
    ");

1 个答案:

答案 0 :(得分:1)

您应该查看docs中的select2事件。

我会使用这两个事件:

  1. 更改 - 更改后执行所需的AJAX事件

    $el.on("change", function (e) {
        $.ajax({...});
    });
    
  2. id - 由于没有select2 create或init事件,我们需要覆盖我们可用的一些公共属性,例如“id”并将我们的AJAX请求放入其中。

    $el.select2({
        id: function (e) { 
            // execute AJAX calls on init
            $.ajax({...});
            return e == undefined ? null : e.id; 
        }
    });
    
  3. 以下是一个小例子:http://jsfiddle.net/dn43uv4c/