我有一个工作中的select2,它通过ajax从远程服务器获取json数据。 我的情况是:第一次打开该应用程序时,用户搜索选择内容,然后将他/她的选择放在会话变量中,因此我希望随后进行任何重新加载,以: -读取会话变量(完成) -根据存储的会话参数(而不是用户键入的内容)进行ajax调用,然后将所选项目设置为ajax的返回值。
我的代码是:
$(document).ready(function()
{
$('#selectedEmployeeId').select2({
dir: "rtl",
width: '100%',
placeholder: 'please type to search',
minimumInputLength: 2,
allowClear: true,
ajax: {
url: '<?= base_url() ?>employee/employees/get_all_employees_json',
dataType: 'json',
data: function (params) {
return { search: params.term };
},
processResults: function (data) {
// Tranforms the top-level key of the response object from 'items' to 'results'
return { results: data };
}
},
language: {
// You can find all of the options in the language files provided in the
// build. They all must be functions that return the string that should be
// displayed.
inputTooShort: function () {
return "at least 2 chars required";
},
noResults: function () {
return 'no result';
},
"searching": function () {
return 'searching...';
}
}
}).on("select2:select", function (e) {
if ($("#selectedEmployeeId").select2('val')) {
var employee_id = $(this).select2('val');
console.log('employee id: ' + employee_id);
$.ajax({
url: "<?= base_url() ?>employee/employees/updateCurrentEmployeeId",
type: "post",
data : {"selected_id" : employee_id,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'}
})
}
});
});
更新:找到解决方法
我想出了将选定的ID和文本放入会话变量中并将此代码放入$(document).ready(function()
中的方法
:
//Check if there is a selected employee in session
var Id= '<?php echo $session_value=(isset($_SESSION['currentEmployeeId']))?$_SESSION['currentEmployeeId']:''; ?>';
var Name= '<?php echo $session_value=(isset($_SESSION['currentEmployeeName']))?$_SESSION['currentEmployeeName']:''; ?>';
//If there is a selected emplpoyee, create option and get it selected
if(Id != '' )
{
var option=jQuery("<option>").attr("value",Id).html(Name);
$('#selectedEmployeeId').append(option);
$('#selectedEmployeeId').val(Id).trigger('select2:select').trigger('change');
}