【问题标题】:Each function through JSON array每个函数通过 JSON 数组
【发布时间】:2013-08-18 03:44:33
【问题描述】:

我正在尝试遍历 JSON 数组,但我不确定在这种情况下如何正确构建 each,有什么想法吗?

这是 $.get 获取的 JSON:

[{"Question":"Write your question here",
    "Answers":
         [{"Answers":"asd",
            "Correct":false},
            {"Answers":"dasdas",
            "Correct":true 
            }
          ]},
{"Question":"Write your question here",
    "Answers":
            [{"Answers":"asdasd",
            "Correct":false
            }
    ] 
}]

这里是 Jquery:

    $.get("data.php", function(data){
    var data = data.replace(/[\[\]']+/g, '')
    $.each(data, function(i, q) {
    var q = new Question(count++, data.Question);
    $.each(data, function(i, val) {
    q.addAnswer(data.Answers, Correct, q);
    });
    });
    questions.push(q);
    });

编辑:

    $.get("data.php", function(data){

        $.each(data, function(i, val) {
            var q = new Question(count++, val.Question);
        questions.push(q);
        });
        $.each(q.Answers, function(i, val) {
            q.addAnswer(val, val.Correct, q);
        questions.push(q);
            });
    });

【问题讨论】:

    标签: jquery json foreach


    【解决方案1】:

    这行导致了一个问题:

    var data = data.replace(/[\[\]']+/g, '')
    

    您正在尝试调用数组的不存在的“替换”方法。


    这部分有两(三)个问题。

    $.each(data, function(i, q) {
        var q = new Question(count++, data.Question);
        $.each(data, function(i, val) {
            q.addAnswer(data.Answers, Correct, q);
        });
    });
    questions.push(q);
    
    1. 您在遍历数组时调用数组中的 each。如果您的 JSON 中有 10 个问题,那么您最终将得到 100 个答案。

      你可能是这个意思。

      .each(val.Answers, function(i, a) {
          q.addAnswer(a.Answers, a.Correct, q);
      });
      
    2. 您正在函数内部创建一个名为q 的变量,并尝试在问题之外访问它。您应该将 questions.push 移动到每个函数中。

    【讨论】:

    • 很好的解释!但是我对此仍然有些麻烦,我对我的问题进行了编辑,但它仍然没有给我任何数据。什么原因? :)
    • 对不起,我在读取 JSON 数据时出错了。我更新了我的答案。
    • 谢谢!我想我现在要解决这个问题!
    猜你喜欢
    • 2020-11-25
    • 2020-10-27
    • 2015-11-04
    • 2018-05-08
    • 2015-11-09
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多