将 API 中的数据显示到 HTML 中时出现问题,纯 Javascript

Issue with displaying data from an API into the HTML, pure Javascript

为此我必须只使用 vanilla JS,没有 jQuery 或框架(这会让生活更轻松)...但这是 JS 文件:

let candidates = [];
const getCandidates = () => {
    axios.get('<a certain endpoint here, the endpoint is good, that is not the problem>')
        .then((response) => {
            for (let i = 0; i < response.data.candidates.length; i++) {
                candidates.push(response.data.candidates[i]);
            }
            console.log(candidates);
            return candidates;
        })
};
getCandidates();

function setAttributes(el, attrs) {
    for(let key in attrs) {
        el.setAttribute(key, attrs[key]);
    }
}

function addCandidatesToHtml() {
    let mainContainer = document.getElementById("candidatesGoHere");
    for (let i = 0; i < candidates.length; i++) {
        let label = document.createElement("label");
        let who = document.createElement("input")
        setAttributes(who, {
            "type": "radio",
            "id": candidates[i].name,
            "name": candidates[i].name,
            "value": candidates[i].name
        })
        label.setAttribute("for", candidates[i].name);
        label.innerHTML = candidates[i].name;
        mainContainer.appendChild(label);
        mainContainer.appendChild(who);
        console.log("in")
    }
}
addCandidatesToHtml();

这是 HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="js/main.js"></script>
    <title>Vote</title>
</head>
<body>

<form id="candidatesGoHere" action="" class="form-control">

</form>

</body>
</html>

问题是循环好像没有运行!想不通为什么会这样,花了很多时间研究和尝试不同类型的循环,但一无所获。

提前致谢!

这仍然是经典的 JavaScript 错误。您在承诺中获取数据,但模块中其余代码的 none 负责该数据。

执行addCandidatesToHtml 时候选数组为空。 getCandidates 中的承诺尚未解决。

只等承诺解决:

getCandidates().then(addCandidatesToHtml)

此外,您的代码很难阅读。如果 getCandidates returns 一个数组,则无需在顶级范围内声明候选数组。考虑将数组作为参数添加到 addCandidatesToHtml 函数。

没有哪个图书馆能让您更轻松地做到这一点。

按如下方式更改您的代码

const getCandidates = async () => {
  let candidates = [];
  return axios
    .get(
      "<a certain endpoint here, the endpoint is good, that is not the problem>"
    )
    .then((response) => {
      console.log(response);
      for (let i = 0; i < response.data.candidates.length; i++) {
        candidates.push(response.data.candidates[i]);
      }
      console.log(candidates);
      return candidates;
    });
};

function setAttributes(el, attrs) {
  for (let key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

async function addCandidatesToHtml() {
  const candidates = await getCandidates();
  let mainContainer = document.getElementById("candidatesGoHere");
  for (let i = 0; i < candidates.length; i++) {
    let label = document.createElement("label");
    let who = document.createElement("input");
    setAttributes(who, {
      type: "radio",
      id: candidates[i].name,
      name: candidates[i].name,
      value: candidates[i].name,
    });
    label.setAttribute("for", candidates[i].name);
    label.innerHTML = candidates[i].name;
    mainContainer.appendChild(label);
    mainContainer.appendChild(who);
    console.log("in");
  }
}
addCandidatesToHtml();
  1. return 来自 getCandidates 函数的承诺,也将函数设为异步
  2. 从 addCandidatedToHTMl 调用 getCandidates 函数并使用 await 等到 promise 被解析,一旦 promise 被解析,您可以将 returned 的 promise 值存储在 candidates 中并可以在函数中使用它