无法使用jQuery从JSON文件中检索数据

时间:2014-05-19 11:47:14

标签: javascript jquery json getjson

我是Javascript和jQuery的新手,我正在尝试使用jQuery中的getJSON方法从JSON文件中检索数据。但是我无法这样做。这是代码:

HTML:

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <title>JSON Test</title>
</head>

<body>
<script type="text/javascript">
    console.log("Hi");
    $.getJSON('red.json', function(data){
    console.log("This is the Data" + data["Live Births"])});
    var response = $.getJSON( "red.json", function() {
        console.log( "success" );
       })
       .done(function() {
         console.log( "second success" );
       })
       .fail(function() {
         console.log( "error" );
       })
       .always(function() {
         console.log( "complete" );
       });
</script>


</body>
</html>

JSON:

{"Live Births" : [
        [11.925, 76.9502],
        [11.896, 76.9492],
        [11.990, 76.9602],
        [11.911, 76.9402],
        [11.978, 76.8902]
    ],

    "Still Births" : [
        [11.986, 76.9402],
        [11.896, 76.9602],
        [11.966, 76.8992],
        [11.916, 76.8902],
        [11.946, 76.9002]
    ]}

等待您的回复。

此致

琼斯

A fiddle Demo to the problem is added

2 个答案:

答案 0 :(得分:1)

我已在我的本地服务器上实现您的代码,它运行正常。 这是我使用的:

<强> HTML:

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <title>JSON Test</title>
</head>

<body>
<script type="text/javascript">
    alert("Hi");
    $.getJSON('red.json', function(data){
    alert("This is the Data" + data["Live Births"])});
</script>


</body>
</html>

唯一的区别是jQuery库的链接(这可能是你身边的问题吗?)。

JSON(red.json):

{
    "Live Births" : [
        [11.925, 76.9502],
        [11.896, 76.9492],
        [11.990, 76.9602],
        [11.911, 76.9402],
        [11.978, 76.8902]
    ],

    "Still Births" : [
        [11.986, 76.9402],
        [11.896, 76.9602],
        [11.966, 76.8992],
        [11.916, 76.8902],
        [11.946, 76.9002]
    ]
}

位于与html文件相同的目录中。

修改

这就是我所做的:

创建一个新文件(index.html)并将html代码粘贴到其中。然后使用您的json数据创建一个新文件red.json。将这两个文件放在一个目录中并打开index.html。

答案 1 :(得分:0)

请尝试使用此

<script type="text/javascript">
  console.log("Hi")
  $(function(){
    $.getJSON('red.json', function(data){
    console.log("This is the Data" + data)});
  });

//请添加这些处理程序

var response = $.getJSON( "red.json", function() {
 console.log( "success" );
})
.done(function() {
  console.log( "second success" );
})
.fail(function() {
  console.log( "error" );
})
.always(function() {
  console.log( "complete" );
});


</script>