创建包含所有 Azure 团队项目的下拉列表

时间:2021-06-30 17:40:03

标签: javascript html jquery azure azure-devops

尝试使用 jQuery 获取集合中我所有团队项目的列表并填充下拉框。我好像遗漏了什么,我的 URL 返回:

"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>

我一整天都在做这个,头撞墙,我搞砸了什么?

1 个答案:

答案 0 :(得分:1)

问题是因为您循环的是基础对象,而不是 value 数组。因此,没有 nameid 属性。

要解决此问题并提高代码质量和性能,您可以使用 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>

请注意,我交换了周围的属性,因此 idvaluenameoption 中的文本,因为这似乎更有意义,除非您的用户识别 GUID 比有意义的名称更容易:)

相关问题