AJAX和Select的问题

Trouble with AJAX and Select

本文关键字:问题 Select AJAX      更新时间:2023-09-26

我正在使用AJAX调用的项目工作,在我的程序中,我有一个选择列表,我需要实现select2,但我不能这样做。我的。js文件中的代码是:

function selectAlumnos(){
   $.ajax({
        type : "GET",
        url : lang + '../../../api/select_alumnos',  //the list of data      
        dataType : "json",
        data : {
                cachehora : (new Date()).getTime()
        }
    }).done(function(response){
        var html = '';
        if(response.state == 'ok'){  //add html to the file view
           html = '<select class="select_1" name="select-allalumnos" id="select-allalumnos" onchange="getIconLocation()" >'; //class to include in select2
           html = html + '<option value="-1">...</option>';
            for(var i in response.alumnos){
                html = html + '<option value="' + response.alumnos[i].id + '" >' + response.alumnos[i].nombre + '</option>';
            } //get the list of the data
            html = html + '</select>'; // put the data in the list
        }
        $('#select-alumnos').html(html); //publish the info in the html file

    });

}

在我的html页面的视图,我有这样的选择校友部分:

<label for="select-alumnos" class="select">Alumno:</label>
<span id="select-alumnos"></span>  //here is the call in the AJAX

在这个文件中(html for view)我也把所有的select2路径到所需的文件,我检查了所有的文件都是ok的,我也包括了类(在我的js文件中相同的类):

   $(document).ready(function() {
        $(".select_1").select2(); 
    });
</script>

我做错了什么,因为我不能得到select2格式在我的列表…?

您在.select_1创建之前调用select2()。在创建元素之后执行(将其放入done函数中)

.done(function(response){
        var html = '';
        if(response.state == 'ok'){  //add html to the file view
           html = '<select class="select_1" name="select-allalumnos" id="select-allalumnos" onchange="getIconLocation()" >'; //class to include in select2
           html = html + '<option value="-1">...</option>';
            for(var i in response.alumnos){
                html = html + '<option value="' + response.alumnos[i].id + '" >' + response.alumnos[i].nombre + '</option>';
            } //get the list of the data
            html = html + '</select>'; // put the data in the list
        }
        $('#select-alumnos').html(html); //publish the info in the html file
        $(".select_1").select2(); 
    });