尝试使用 jQuery 获取集合中所有团队项目的列表并填充下拉框。我似乎遗漏了一些东西,我的网址返回此:
"count": 78,
"value": [
{
"id": "0bf6cce2-cac1-412e-8617-43d808249a28",
"name": "project1",
"description": "one",
"url": "https://devops.xxx.com/tfs/xxx/_apis/projects/0bf6cce2-cac1-412e-8617-43d808249a28",
"state": "wellFormed",
"revision": 1064067,
"visibility": "private",
"lastUpdateTime": "2021-03-31T14:28:43.827Z"
},
{
"id": "cc504f31-3568-4b62-9750-7e4d43574ce6",
"name": "project2",
"description": "2nd project",
"url": "https://devops.xxx.com/tfs/xxx/_apis/projects/cc504f31-3568-4b62-9750-7e4d43574ce6",
"state": "wellFormed",
"revision": 1063717,
"visibility": "private",
"lastUpdateTime": "2015-09-11T03:48:24.99Z"
}
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select id="team-projects" name="projects">
</select>
</body>
<script>
let dropdown = $('#team-projects');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose Team Project</option>');
dropdown.prop('selectedIndex', 0);
const url = 'https://devops.xxx.com/tfs/xxx/_apis/projects?api-version=5.0';
// Populate dropdown with list of team projects
$.getJSON(url, function (value) {
$.each(value, function (key, value) {
dropdown.append($('<option></option>').attr('value', value.name).text(value.id));
})
});
</script>
</html>
我一整天都在用头撞墙,我搞砸了什么?
最佳答案
问题是因为您正在循环访问基础对象,而不是 value
数组。因此,没有 name
或 id
属性。
要解决此问题并提高代码质量和性能,您可以使用 map()
构建 option
HTML 字符串数组,将其附加到下拉列表中单一 DOM 操作。试试这个:
let $dropdown = $('#team-projects').empty();
$dropdown.append('<option selected="true" disabled value="">Choose Team Project</option>').val('');
// In the AJAX callback:
let response = {count:78,value:[{id:"0bf6cce2-cac1-412e-8617-43d808249a28",name:"project1",description:"one",url:"https://devops.xxx.com/tfs/xxx/_apis/projects/0bf6cce2-cac1-412e-8617-43d808249a28",state:"wellFormed",revision:1064067,visibility:"private",lastUpdateTime:"2021-03-31T14:28:43.827Z"},{id:"cc504f31-3568-4b62-9750-7e4d43574ce6",name:"project2",description:"2nd project",url:"https://devops.xxx.com/tfs/xxx/_apis/projects/cc504f31-3568-4b62-9750-7e4d43574ce6",state:"wellFormed",revision:1063717,visibility:"private",lastUpdateTime:"2015-09-11T03:48:24.99Z"}]};
let options = response.value.map(o => `<option value="${o.id}">${o.name}</option>`);
$dropdown.append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select id="team-projects" name="projects"></select>
请注意,我交换了属性,因此 id
是 value
,name
是 option
中的文本> 因为这似乎更有意义,除非您的用户比有意义的名称更容易识别 GUID :)
关于javascript - 创建包含集合中所有 Azure 团队项目的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68199342/