javascript - 访问 Javascript 变量中的 JSON 对象

标签 javascript json

我正在使用 JSON 制作一个问答游戏,但我陷入了困境。首先,我可以从 JSON 中提取数据,并在完成文档后将其显示在列表中,如下所示:

$.getJSON('/trivia.json', function(data) {
    var items = [] 
    $.each(data, function (item, i) {
        items.push('<li id="' + i.order + '">' + i.question + ' - ' + i.choices + i.correct +  '</li>');
    });

    $('<ul/>', {
        'class': 'my-new-list',
        html: items.join('')
    }).appendTo('#example');

});

这可以很好地创建问题和答案列表,因此我可以确认我正在正确调用本地 JSON 文件。

我的下一步是将问题和答案数据存储在我的 Javascript 变量中,以便进行测验。当我进行示例测验时,我像这样存储数据:

var quiz = [
    {
        "question" : "Q1: Who came up with the theory of relativity?",
        "choices" : [
                                "Sir Isaac Newton",
                                "Nicolaus Copernicus",
                                "Albert Einstein",
                                "Ralph Waldo Emmerson"
                            ],
        "correct" : "Albert Einstein",
    }]; 

我不希望问题是静态的,所以我希望 JSON 接管提供问题和选择。

我尝试为测验变量调用appendTo函数,但它并没有像我创建列表时那样传递数据。关于如何获得适用于 var 测验的问题、选择和正确数据集,有什么想法吗?

最佳答案

您可以更新代码,将 Ajax 请求中捕获的数据添加到 quiz 变量中,并迭代选项以打印它们,如以下代码所示:

var quiz = [
    {
        "question" : "Q1: Who came up with the theory of relativity?",
        "choices" : [
                                "Sir Isaac Newton",
                                "Nicolaus Copernicus",
                                "Albert Einstein",
                                "Ralph Waldo Emmerson"
                            ],
        "correct" : "Albert Einstein",
    }];     
$.getJSON('/trivia.json', function(data) {
    var items = [] 
    $.each(data, function (item, i) {
        var q = {"question": i.question, "correct": i.correct, "choices": []};
        var choicesStr = ""; 
        $.each(i.choices, function (it, choice) {
            choicesStr += "<span>choice</span></br>";
            q.choices.push(choice);
        }
        quiz.push(q);
        items.push('<li id="' + i.order + '">' + i.question + ' - ' + choicesStr  + i.correct +  '</li>');

    });

    $('<ul/>', {
        'class': 'my-new-list',
        html: items.join('')
    }).appendTo('#example');

});

关于javascript - 访问 Javascript 变量中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26812257/

相关文章:

javascript - create-react-native-app 上的 Knex.js

java - 在改造中发送仅包含字符串的 JSONArray

android - 向服务器发送 JSON 数据和图像

javascript - 如何解决 javascript 中 JSON 中的意外标记 { 语法错误

C# JSON 解析问题

javascript - 使用 jquery 使一个函数在具有相同类的所有 div 中工作

javascript - 带有音频标签的多个播放/暂停按钮

javascript - UI-router 干扰 $http 后端单元测试,angularjs

javascript - 如何将子元素附加到悬停元素?

php - json_encode 不会转义换行符