为什么此HTTP请求返回数组长度而不是内容?

时间:2017-03-25 20:59:34

标签: javascript jquery arrays

我正在处理一些包括从API异步获取数据的内容。一切都很顺利,除非我尝试将正确的答案推送到错误的答案数组中。返回的所有内容都是相应的数组长度而不是内容。我做错了什么?

以下是HTML和jQuery代码:

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>repl.it</title>
        <link href="index.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
      <div>
        <h3>Answers</h3>
        <ol></ol>
      </div>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="index.js"></script>
    </body>
</html>

的jQuery

$(() => {
  $.ajax({
    method: "GET",
    url: "https://opentdb.com/api.php?amount=50&category=18",
    async: true,
    success: (data) => {
      let results = data.results;
      $.each(results, (i, difficulty, question) => {
        difficulty = results[i].difficulty;
        question = results[i].question;
        correctAnswer = results[i].correct_answer;
        answers = results[i].incorrect_answers;

        $("ol").append(`
          <li>${answers.push(correctAnswer)}</li>
        `);
      });
    }
  });
});

1 个答案:

答案 0 :(得分:1)

检查the docs是否有推送功能。

  

返回值

     

调用方法的对象的新长度属性。

在您的函数结束时,您正在将correctAnswer推送到答案,这些答案将返回答案数组的长度,并且您将在html中显示该答案。这很自然。

先按,然后创建html标签。

检查一下;

&#13;
&#13;
$(() => {
  $.ajax({
    method: "GET",
    url: "https://opentdb.com/api.php?amount=50&category=18",
    async: true,
    success: (data) => {
      let results = data.results;
      $.each(results, (i, difficulty, question) => {
        difficulty = results[i].difficulty;
        question = results[i].question;
        correctAnswer = results[i].correct_answer;
        answers = results[i].incorrect_answers;

        answers.push(correctAnswer)
        $("ol").append(`
          <li>${correctAnswer}</li>
        `);
      });
    }
  });
});
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="index.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div>
    <h3>Answers</h3>
    <ol></ol>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="index.js"></script>
</body>

</html>
&#13;
&#13;
&#13;