2015-08-13 72 views
0

我使用AJAX調用項目工作,並在我的程序中我有一個選擇列表,我需要實現select2,但我不能這樣做。我在我的.js文件的代碼是:AJAX和選擇的問題

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頁面我有選擇,alumnos部分是這樣的:

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

在這個文件(HTML爲查看)我也把所有的select2路徑到所需的文件,我檢查所有的文件都沒問題,我也包括類(在我的js文件中的同一類):

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

我做錯了什麼,因爲我無法獲得我的清單中的select2格式...?

回答

0

您在.select_1創建之前致電select2()。在創建元素(將其放入完成函數中)後執行此操作

.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(); 

    });