javascript - 使用索引访问 AJAX JSON 属性在 promise 中给出未定义

标签 javascript jquery json ajax mongodb

所以我有测验应用程序,它使用 MongoDB 与我在服务器上的 API 对话。

我想像这样访问它的响应索引:

setTimeout(() => {

  axios.get('/api/ninjas')
    .then(function (questions) {
      var data = questions.data;


  $.each(data, function(index, value) {
    /*thequestion = [
      new Question(value.the_question[index], value.the_choices[index], value.the_answer[index])

    ]*/
    console.log(value[index].the_question);
    quiz = new Quiz(thequestion)
    populate()
  })
}), 2000});

但我得到 Uncaught (in promise) TypeError: Cannot read property 'the_question' of undefined

如果我删除 [index],那么我会在控制台中得到问题文本。我也试过把 [index] 放在最后,就像这样 console.log(value.the_question[index]); 但后来我只得到一个字母屏幕。

基本上我的 MongoDB 集合中有两个对象。每个都包含 the_question 字符串、the_choices 数组和 the_answer 字符串。我想在屏幕上一次输出一个问题及其答案选择,但是当我重新加载页面时,我只得到数据库集合中的最后一个问题和一次所有的答案选择,即使它们应该每个问题不超过 3 个按钮。当数据库中只有一个问题时,它工作正常。

数据库中的一个问题:

enter image description here

DB collection中不止一个问题:

enter image description here

所以我想使用索引一次输出一个问题,但是在使用时出现错误。怎么了?

我必须提到它工作正常我没有为此使用数据库。只是 javascript 中的全局变量。像这样,我一次得到一个问题

let thequestion = [
  new Question("Which one of the three is a programming language?", ["Javascript", "HTML", "CSS"], "Javascript"),
  new Question("Is NodeJS is a front end or back end framework?", ["Back end", "Front End"], "Back end"),
  new Question("Is JAVA object oriented language?", ["Yes", "No"], "Yes")
]

我的数据库是这样的:

enter image description here

编辑:整个前端源代码:

https://codepen.io/Limpuls/pen/rYYLro?editors=1010

最佳答案

您可以尝试以下方法,如果这不起作用,您能否使用控制台日志的输出更新您的问题,以便我们可以看到您的 API 收到的问题的格式?

setTimeout(() => {
  axios.get('/api/ninjas')
  .then(function (questions) {
    console.log(
      "received questions:"
      ,JSON.stringify(questions,undefined,2)
    );
    quiz = new Quiz(//create a quiz
      (questions.data || [])//map question data to Question type
      .map(
        function (question) {
          return new Question(
            question.the_question, 
            question.the_choices, 
            question.the_answer
          );
        }
      )
    );
    populate()
  })
  , 2000
});

为什么要等待 2 秒才能获取数据?如果这是在页面加载时,那么你可以尝试 $(document).ready 但我认为你不必等待文档准备好开始获取问题(可能只填充):

$(document).ready(x=>populate());

关于javascript - 使用索引访问 AJAX JSON 属性在 promise 中给出未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340856/

相关文章:

javascript - 如何使用 JavaScript 在此处缩放存储在数组值中的所有诺基亚 map 标记

javascript - jQuery 检测加载时是否选择了单选按钮

javascript - 如何操作JSON数据?

javascript - 防止空输入传递空字符串javascript

javascript - 当 JavaScript 动态添加行时,单选按钮功能无法正常工作

javascript - 如何在ajax post请求laravel中传递 token ?

javascript - 当在 AJAX、Jquery 中使用 GET 更新数据库时,如何反射(reflect)表上的更新

json - 在 Swift 中循环遍历 JSON 对象

Android Retrofit 在获取 jsonobject 时总是返回 boolean 类型的 false 值

javascript - 是否可以以一定 Angular 重复平铺背景?