0

我正在尝试从下面带有“$.each”的 JSON 文件中获取值,但它没有给我使用下面使用的 $.each 方法的任何值,有没有人有任何建议我可以如何使它正常工作? 我想用 Question 值获取每个对象 [Question] 的信息,然后为每个问题提供答案。

JSON:

[
    {
        "Question": "Question 1",
        "Answers": [
            {
                "Answers": "Answer 1",
                "Correct": false
            },
            {
                "Answers": "answer2",
                "Correct": true 
            }
        ]
    },
    {
        "Question": "Question 2",
        "Answers": [
            {
                "Answers": "An Answer",
                "Correct": false
            }
        ] 
    }
]

jQuery:

$(document).ready(function () {   
    $.get("data.php", function(data) {
        $.each(data, function(i, val) {
            var q = new Question(count++, val.Question);
            questions.push(q);
        });

        $.each(val.Answers, function(i, a) {
            q.addAnswer(a.Answers, a.Correct, q);
            questions.push(q);
        });
    });

感谢您的帮助!


更新:

$(document).ready(function () {   
    $.get("data.php?campaign_id=39&social_user_id=1192&edit=true", function(data){

        var questions = [];
        $.each(data, function(i, val) {
            var q = new Question(count++, val.Question);
            questions.push(q);

            $.each(val.Answers, function(i, a) {
                q.addAnswer(a.Answers, a.Correct, q);

            });
        });
    });
});
4

2 回答 2

3

如果val要从第二个访问,则需要嵌套循环。您似乎放错了右括号。

var questions = [];
$.each(data, function(i, val) {
    var q = new Question(count++, val.Question);
    questions.push(q);

    $.each(val.Answers, function(i, a) {
        q.addAnswer(a.Answers, a.Correct, q);
    });
});
process(questions); // callback
于 2013-08-18T13:40:20.183 回答
0

我现在设法让它工作!

这是我使用的代码:

   $.get("data.php",
   function(data) {
       $.each(data, function(q ,val) {
           var q = new Question(count++, val.Question);
           questions.push(q);
               $.each(val.Answers, function(a, val) {
            q.addAnswer(val.Answers, val.Correct, q);
           });
       });
   }, "json");
于 2013-08-18T16:20:10.640 回答