JSON访问不起作用

时间:2016-05-30 06:27:43

标签: javascript html json

我试图从我的HTML文件中访问JSON文件,并且我正在使用JQuery: $.getJSON( "en.json", function( data ) { console.log(data.age); });

这似乎不起作用。我使用Xampp来托管我的本地服务器,并且在某处读到JSON在本地存储时不起作用。这可能是与此相关的问题吗?

谢谢

HTML code:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
        <script>
            alert();            
            $.getJSON( "en.json", function( data ) {
                console.log(data.age);
            });
        </script>
    </head>
    <body>
        <div class="test">
            Hi
        </div>
    </body>
</html>

JSON文件:

{
    "add-school" : "Add School",
    "age" : "Age",
    "age-months" : "Age (in months)",
    "age-years" : "Age (in years)",
    "all-classes" : "All Classes",
    "audio": "Audiometry",
    "bmi" : "BMI",
    "bp" : "BP"
}

2 个答案:

答案 0 :(得分:1)

我能够在控制台中查看结果“Age”。我在我的机器上运行Tomact Apache 7.0版本并将文件(.html和.json)保存在webapps文件夹内的同一文件夹中。

为了查看网页,我使用的网址是

http://localhost:8080/Foldername/Json.html 我可以在控制台中看到console.log(data.age)的结果

答案 1 :(得分:0)

一切看起来都很好。确保 json 文件与 html 文件位于同一位置。如果它没有改变$.getJSON()函数中的路径。