select2 ajax dynamically fetches data and echoes it

There is a requirement: to assign roles to an employee, you must first obtain the roles that the employee already has, and obtain a list of all roles.

The specific effects are as follows

Implementation steps:

1. Load all roles list

Because it's a static pop-up box, you can't send a request to load the role list every time you open the static box, and then the page initialization should be completed.

         * Page initialization
        $(function () {
         function initRolesSelect() {
                url: '/admin/sys/role/list',
                success: function (res) {
                        theme: "bootstrap",
                        multiple: true, //Open multiple selection
                        data:,  //Data returned
                        minimumResultsForSearch: -1 //No search


According to the official document, as long as the format returned is

{ "results": [ { "id": 1, "text": "Option 1" }, { "id": 2, "text": "Option 2", "selected": true }, { "id": 3, "text": "Option 3", "disabled": true } ] }

select2 in this format is automatically rendered. Selected indicates whether it is selected when loading, and disabled indicates that it cannot be edited. Of course, you can also customize the template. Because the list of roles needs to be loaded at page initialization time, the roles already owned by the employee cannot be returned. The defined return format is:

console.log( //Data returned by back end

(4) [{...}, {...}, {...}, {...}]
0: {id: 1, text: "system administrator"}
1: {id: 4, text: "staff"}
2: {id: 5, text: "Boss"}
3: {id: 7, text: "Code farming"}
length: 4

2. Find the role already owned by the personnel id and echo it

//Echo data 
function echoSelect2(dom,value){
        $(dom).append(new Option(,, false, true));


In this way, a new option will be created for echo, but there will be more options in the drop-down list.


Finally, check the official documents: $('ාselectrole'). Val (['1 ','2']); $('ාselectrole'). Trigger ('change '); echo can be realized through the change event monitoring in the following table of the incoming array.

         * Assign role echo
         * @param id
        function allotRoleBtn(id) {
            $('#selectRole').val(null).trigger('change'); / / clear the static box before loading.
            if (id) {
                    url: '/admin/sys/user/allotsearch',
                    data: {id: id},
                    success: function (res) {
                        $('#allotRoleModal').modal('show'); / / open the static box
                        $('#allotRoleFrom').setForm(; / / echo user name and nickname

                        var role =;//Get the role owned by the employee
                        var roles = []; //Define an empty array to hold the role id

                        if (role != "") {
                            $.each(role, function (index, role) {






Posted on Tue, 03 Dec 2019 18:08:00 -0500 by s1yman