在Javascript变量中访问JSON对象

时间:2014-11-08 00:21:46

标签: 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接管提供问题和选择。

我试图为quiz var调用appendTo函数,但是它没有像我创建列表时那样传递数据。关于如何通过var测验来解决问题,选择和正确数据集的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以更新代码,将Ajax请求中的绘制数据添加到测验变量,并迭代选择以打印它们,如下面的代码:

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');

});
相关问题