我正在进行 Ajax 调用,该调用返回员工姓名和 ID。这些是我希望在模式弹出窗口的多选框中可用的数组。如果可能,我还希望显示选定的值?
我的控制台日志显示:
Object {employees: Object}
employees:Object
data: Array(2)
0: Object
id: 1
name: "Sam Test 1"
__proto__: Object
1: Object
id: 2
name: "Joe Test 2"
__proto__: Object
我的ajax调用如下:
$(document).ready(function() {
$('.editApptModal-button').click(function() {
var appointmentID = $(this).attr('data-appointmentID');
console.log(appointmentID);
$.ajax({
type: 'ajax',
method: 'get',
url: '/ajax',
async: false,
dataType: 'json',
success: function(response) {
console.log(response);
$.each(response.employees.data, function(key, value) {
$('select').append($("<option/>", {
value: key,
text: value
}));
});
$('#editApptModal').modal('show');
},
error: function(response) {
alert('Could not displaying data' + response);
}
});
});
});
那么我需要在这里做什么才能将 id 放在选项值中,将 name 放在选项文本中?
$.each(response.employee.data, function(key, value) {
$('select').append($("<option/>", {
value: key,
text: value
}));
});
更新
使用 console.log(JSON.stringify(response));
:
{
"employees": {
"data": [{
"id": 1,
"name": "Sam Test 1"
}, {
"id": 2,
"name": "Joe Test 2"
}]
}
}
选择框
<select multiple="multiple" name="employees" class="form-control search-select">
<option value=""></option>
</select>
最佳答案
你需要做这样的事情:
$.each(response.employees.data, function(key, value) {
$('select').append($("<option>", {
value: value.id,
text: value.name
}));
});
关于javascript - 成功 Ajax 后将数组/多选数据放入模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44873463/