【问题标题】:Yii2, Select2, Optgroup with Ajax doesn't workYii2、Select2、带有 Ajax 的 Optgroup 不起作用
【发布时间】:2015-12-13 23:06:30
【问题描述】:

我正在使用 Yii2Select 2。我尝试使用从 ajax 加载的 optgroup 示例。浏览器发送请求,但在我尝试打印时没有显示任何内容。
代码如下。

<?= Select2::widget([
        'name' => 'cycle',
        'pluginOptions' => [
            'multiple' => true,
             'ajax' => [
                 'url' => Url::to(['films-json/cycle-channel']),
                 'dataType' => 'json',
                 'data' => new JsExpression('function(params) { return {q:params.term}; }')
             ],
        ],
    ]);
?>

循环通道操作返回 100% 工作 json。当我尝试将 id 用作静态的(下面的代码)时,它正在工作。但我需要动态搜索。

<?= Select2::widget([
        'name' => 'cycle',
        'data' => FilmsJsonController::actionCycleChannel(''),
        'pluginOptions' => [
            'multiple' => true,
        ]
    ]);
?>

我做错了什么?

【问题讨论】:

    标签: jquery ajax yii2 yii-extensions


    【解决方案1】:

    您的问题是您没有告诉小部件对从服务器返回的数据执行任何操作。您需要在插件选项中添加类似的内容;

    'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
            'templateResult' => new JsExpression('function(city) { return city.text; }'),
            'templateSelection' => new JsExpression('function (city) { return city.text; }'),
    

    您显然需要将 city.text 更改为您希望在选择下拉菜单中显示的任何文本。

    控制器需要以插件期望的格式返回json数据。 codumentation 显示类似这样的内容;

    public function actionSearch($q = null, $id = null) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $out = ['results' => ['id' => '', 'text' => '']];
            if (!is_null($q)) {
                $query = new Query;
                $query->select('id, title AS text')
                        ->from('city')
                        ->where(['like', 'title', $q])
                        ->limit(20);
                $command = $query->createCommand();
                $data = $command->queryAll();
                $out['results'] = array_values($data);
            } elseif ($id > 0) {
                $out['results'] = ['id' => $id, 'text' => City::find($id)->title];
            }
            return $out;
        }
    

    更多示例请参见the documentation

    【讨论】:

    • 我尝试过使用模板,但它会在显示“templateSelection”返回片刻后立即关闭下拉菜单。如果我只使用静态“数据”参数,它就可以完美运行。我正在使用这样的 json: {"Gr1":{"1":"Element1","6":"Element6"},"Gr2":{"3":"Element3"},"Gr3":{ "2":"Element2","5":"Element5"},"Gr4":{"4":"Element4"}}
    • 啊,你的问题,你的json数据需要是插件所期望的格式。您已经调用了数据 Gr!、Gr2 等。json 需要只是“结果”,然后是一个数组(如果是 ids 和 text)。我已更新我的答案以包含所需的数据格式。
    猜你喜欢
    • 2018-02-24
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2015-06-14
    • 1970-01-01
    • 2020-04-14
    • 2017-08-22
    相关资源
    最近更新 更多