JSON未定义结果

时间:2017-09-12 16:43:52

标签: javascript json

我有以下脚本,它有一个有趣的互动。

        $(document).ready(function () {
            $.get('data/experiments.json', function (data) {
                trialsData = data.experiments;
                console.log(trialsData);
                console.log(data);
                currentTrial = 0;
                totalNumberOfTrials = data.experiments.length;
                $('.js-expt-num-trials').text(totalNumberOfTrials);
                data.experiments.push(headers);
                next();
                pid = ACPToolKit.getCurrentParticipantId();
            })
        });

当我console.log(data)时,它会返回实际且正确的数据

{
    "experiments": [
        { 
            "technique": "AUTOCOMPASTE", 
            "granularity": "sentence",
            "data_file": "data/texts.json",
            "stimuli": "What is acceptor atoms?" 
        },
        { 
            "technique": "AUTOCOMPASTE", 
            "granularity": "paragraph",
            "data_file": "data/texts.json",
            "stimuli": "What is AC coupling? Circuit that passes an AC signal while blocking a DC voltage." 
        },
        { 
            "technique": "AUTOCOMPASTE", 
            "granularity": "phrase",
            "data_file": "data/texts.json",
            "stimuli": "number of positive charges" 
        },
        { 
            "technique": "TRADITIONAL", 
            "granularity": "sentence",
            "data_file": "data/texts.json",
            "stimuli": "What is acceptor atoms?" 
        },
        { 
            "technique": "TRADITIONAL", 
            "granularity": "paragraph",
            "data_file": "data/texts.json",
            "stimuli": "What is AC coupling? Circuit that passes an AC signal while blocking a DC voltage." 
        },
        { 
            "technique": "TRADITIONAL", 
            "granularity": "phrase",
            "data_file": "data/texts.json",
            "stimuli": "number of positive charges" 
        }        
    ]
}

然而,当我console.log(trialsData)或甚至console.log(data.experiments)时,它返回undefined。不用说data.experiments.lengthtrialsData.length也会返回错误Uncaught TypeError: Cannot read property 'length' of undefined

我不知道我在这里做错了什么。我非常确定data.experiments是正确的语法

0 个答案:

没有答案