2017-10-20 40 views
0

我想通過使用jQuery將通過ajax返回的一些用戶名加載到下拉菜單中。結果正在成功進入下拉菜單,但所有數據都只進入一個選項標籤。我希望數據位於不同的選項標籤中。從一個數組中填充項目到不同的選項標籤

目前的下拉菜單看起來像這樣

1,名稱,NAME3,NAME4

但我想爲:

名1

名2

NAME3

姓名4

下拉哪裏我把結果:

<div class="form-group"> 
    <select name="name" class="form-control" id="employee_select"> 
</select> 
</div> 

的jQuery:

//send value via GET to URL 
    var get_request = $.ajax({ 
     type: 'GET', 
     url: '/users', 
     data: {User:User} 
    }); 

    // handle response 
    get_request.done(function(data){ 

    // Data returned 
    dataReturned = data; 

    // Log data 
    console.log($.type(dataReturned)); // response is string in the form of 
             // Name1 
             // Name2 

    // Convert to an array 
    dataArray = [dataReturned] 

    // Create a new array 
    newArray = []; 

// Populate newArray with items 
for(i=0;i<dataArray.length;i++){ 
    if(typeof(dataArray[i])=='string'){ 
    newArray.push(dataArray[i]) 
} 
} 
//console.log(newArray); 
console.log($.type(newArray)); // an array is returned in the form of ["Name1,Name2,Name3,Name4"] 

// Loop through newArray 
$.each(newArray, function(index, value) { 
$('#employee_select').append("<option>"+ value + "</option>"); 
}) 

謝謝。

+0

你需要修復的結果從用戶..份額未來如何從URL – guradio

+0

檢查您的返回的字符串不包含\ n \ n通過的結果 - 這時候你把它分解使用\ N - 會創建empy數組元素,然後將其傳遞給選項。如果您使用console.log(str),那麼您將能夠在其拆分之前看到返回的數據。 – gavgrif

回答

0

有可能這樣做的更優雅的方式,但...

如果你所推的每個結果到一個數組,然後在數組跑了一個循環的每個項目檢查,看看每一項都是一個字符串。那個成功的結果,你推入最後一個數組。

for(i=0;i<array.length;i++){ 
    if(typeof(array[i])=='string'){ 
    newArray.push(array[i]) 
} 
} 
+0

感謝您的幫助! 我已更新我的問題。你能幫忙嗎? – LinuxUser

相關問題