Yii2 kartik typeahead - 获取建议数量

Yii2 kartik typeahead - get number of suggestions

我在一个视图中为 Yii2 使用 kartik 的 typeahead 小部件:

echo \kartik\typeahead\Typeahead::widget([
    'name'          => 'serial_product',
    'options'       => [
        'placeholder' => 'Filter as you type ...',
        'autofocus'   => "autofocus"
    ],
    'scrollable'    => TRUE,
    'pluginOptions' => [
        'highlight' => TRUE,
        'minLength' => 3
    ],
    'dataset'       => [
        [
            'remote' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
            'limit'  => 10
        ]
    ],
    'pluginEvents'  => [
        "typeahead:selected" => "function(obj, item) { add_item(item.id); return false;}",
    ],
]);

在检索到远程数据集以执行 javascript 函数后,如何获取已加载建议的数量:

displaynumber(NUMBEROFSUGGESTIONS);

在检查了 kartiks 小部件的来源后,我想出了以下解决方案:

echo \kartik\typeahead\Typeahead::widget([
    'name'          => 'serial_product',
    'options'       => [
        'placeholder' => 'Filter as you type ...',
        'autofocus'   => "autofocus",
        'id'          => 'serial_product'
    ],
    'scrollable'    => TRUE,
    'pluginOptions' => [
        'highlight' => TRUE,
        'minLength' => 3
    ],
    'dataset'       => [
        [
            'remote' => [
                'url'  => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
                'ajax' => ['complete' => new JsExpression("function(response)
                    {
                        jQuery('#serial_product').removeClass('loading');
                        checkresult(response.responseText);
                    }")]
            ],
            'limit'  => 10
        ]
    ],
    'pluginEvents'  => [
        "typeahead:selected" => "function(obj, item) { checkresult2(item); return false;}",
    ],
]);

其中 response.responseText 包含来自服务器 (json) 的响应。

function checkresult(response) {
    var arr = $.parseJSON(response);
    console.log(arr.length);
}

有了这个功能,我可以得到从服务器发送的建议的数量。