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>");
})
謝謝。
你需要修復的結果從用戶..份額未來如何從URL – guradio
檢查您的返回的字符串不包含\ n \ n通過的結果 - 這時候你把它分解使用\ N - 會創建empy數組元素,然後將其傳遞給選項。如果您使用console.log(str),那麼您將能夠在其拆分之前看到返回的數據。 – gavgrif