我正在通过select2 kartik小部件获取通知,并且一切工作都很好,现在我试图修改代码以在下拉div中获取数据,但是我对此并不了解。
这是我在视图中修改的代码
<div class="dropdown-menu animated flipInX">
<div class="dropdown-body niceScroll ">
<!-- Start notification list -->
<div class="media-list small">
<a href="#" class="media">
<?php
$notificationUrl = Url::to(['site/notification-list']);
echo Select2::widget([
'name' => 'state_800',
'pluginOptions' => [
'ajax' => [
'url' => $notificationUrl,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term, page:params.page || 1}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(product) {;return product.text; }'),
'templateSelection' => new JsExpression('function (subject) { return subject.text; }'),
],
]);
?>
</a>
</div> .......
这是我在检索数据时将要执行的操作;所以我的问题是如何在下拉div中显示数据
public function actionNotificationList($page, $q = null, $id = null) {
$offset = ($page - 1) * 10;
Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
$query = new Query;
$query->select(['notification_id as id', new Expression("notification_text AS text")])
->from('notification')
->offset($offset)
->limit(10);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
$out['pagination'] = ['more' => !empty($data) ? true : false];
return $out;
}
谢谢。
答案 0 :(得分:0)
据我所知,您正在尝试动态更新select2内的选项,如果正确,则可以使用javascript更新select2选项。
您的通知看起来像是来自某些数据库表,您可以发送ajax调用以检查是否有未读的通知,并以JSON格式返回通知列表,并在运行时更新Selec2
选项
我可以证明通过单击按钮,因为ajax将无法在SO上实现,因此可以用ajax调用替换按钮click
并将通知传递给refreshDataSelect2
函数将会更新选项。
$('.notifications').select2({
placeholder: 'Select an option',
'width': '100%'
});
$.fn.refreshDataSelect2 = function(data) {
this.select2('data', data);
// Update options
var $select = $(this[0]);
var options = data.map(function(item) {
return '<option value="' + item.id + '">' + item.text + '</option>';
});
$select.append(options.join('')).change();
};
$("#add").on("click", function() {
let data = [{
id: $('.notifications').children('option').length + 1,
text: "A New Message number " + $('.notifications').children('option').length
}]
$(".notifications").refreshDataSelect2(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<select name="notifications" class="notifications">
<option>some Message</option>
<option>Admin Message</option>
<option>Private Message</option>
</select>
<button id="add">Add Message</button>