简体   繁体   中英

Bootstrap typeahead does not work with ajax response

I'm using the Yii Booster extension that wraps the Twitter Bootstrap 2.3.2 library into a usable Yii extension. I have a typeahead field, which fetches data using AJAX calls (using jQuery's ajax() function). The code that creates the typeahead field is:

$this->widget('bootstrap.widgets.TbTypeahead', array(
  'model'=>$expense,
  'attribute'=>'afm',
  'htmlOptions'=>array('autocomplete'=>'off'),
  'options'=>array(
    'source'=>'js:function(query, process) {
      $.ajax({url: "' . $urlAfm . '", data: {query: query}, dataType: "json" })
      .done(function(data) {
        return process(data);
      })}',
    'updater'=>'js:function(item) {
      return item;
    }',
    'highlighter'=>'js:function(item) {
      return item;
    }',
  )));

The corresponding controller action that returns the JSON data is:

public function actionAjxGetAFM($query = '') {
  if (Yii::app()->request->isAjaxRequest && trim($query) != '') {
    $companies = Yii::app()->db->createCommand('SELECT name FROM company WHERE afm '
      . 'LIKE :match LIMIT 10')->queryColumn(array(':match'=>$query . '%'));
    Yii::trace(print_r(CJSON::encode($companies), true));
    echo CJSON::encode($companies);
    Yii::app()->end();
  }
  echo '0';
}

No matter what I tried, no list appears after entering the first character. What am I doing wrong?

The JSON response from the controller action is something like:

["\u039b\u03bf\u03cd\u03c1\u03b4\u03b1\u03c2 \u0392\u03b1\u03c3\u03af\u03bb\u03b5\u03b9\u03bf\u03c2","\u039c\u03bf\u03c5\u03c1\u03b1\u03c4\u03af\u03b4\u03bf\u03c5 \u039c\u03b1\u03c1\u03af\u03b1","\u03a0\u03bf\u03bb\u03c5\u03c7\u03c1\u03cc\u03bd\u03b7\u03c2 \u039b\u03bf\u03cd\u03c1\u03b4\u03b1\u03c2"]

instead of this

'htmlOptions'=>array('autocomplete'=>'off'),

change it to

'htmlOptions'=>array('autocomplete'=>'on'),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM