0

我有一个关于 JSON Jquery 的基本问题,它接缝我有点卡在提取数组对象的点上。我下面的代码是用javascript编写的,我只是想澄清一下我在这里可能做错了什么。

<?php  
$nor = $_SESSION["north"];
$sou =  $_SESSION["south"];
$eas =  $_SESSION["east"];
$wes = $_SESSION["west"];

session_destroy();

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
<html>  
  <head>  
    <title>jQuery JSON test</title>  
  </head>  

  <body>  


<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>  
    <script type="text/javascript">  
    var north = "<?php echo $nor ?>";
        var south = "<?php echo $sou ?>"; 
        var east = "<?php echo $eas ?>";
        var west = "<?php echo $wes ?>";

        document.write(north,south,east,west);


    $(document).ready(function(){

        alert("begin loop");
        $.getJSON('http://api.geonames.org/earthquakesJSON?north=' + north + ' &south=' + south + '&east=' + east + '&west=' + west +'&callback=?',
        function(data){
            alert(data.earthquakes);
    });
})

    </script>  

  </body>  
</html>  

所以当我使用 alert(data.earthquakes); 我得到未定义的操作,这很好,但我知道我在这里得到了回复。然而 JSON 的架构如下:

{"earthquakes": [
     {"eqid":"2007hear","magnitude":8.4,"lng":101.3815,"src":"us","datetime":"2007-09-12 09:10:26","depth":30,"lat":-4.5172},
     {"eqid":"2007aqbk","magnitude":8,"lng":156.9567,"src":"us","datetime":"2007-04-01 18:39:56","depth":10,"lat":-8.4528},
     {"eqid":"2007hec6","magnitude":7.8,"lng":100.9638,"src":"us","datetime":"2007-09-12 21:49:01","depth":10,"lat":-2.5265}
]}

所以我尝试了不同的方法来提取信息,例如alert(data.earthquakes[1].eqid);and alert(data.earthquakes.eqid[1]);,但是我没有得到想要的专用数组。

有人可以指导我

  1. 如何适当地获得所需的架构结果以及
  2. 如果我想使用数组和for循环将所有元素提取到本地数组中,

怎么做?

4

1 回答 1

1

如果您的 JSON 对象定义如下:

var jsonData = {"earthquakes": [
         {"eqid":"2007hear","magnitude":8.4,"lng":101.3815,"src":"us","datetime":"2007-09-12 09:10:26","depth":30,"lat":-4.5172},
         {"eqid":"2007aqbk","magnitude":8,"lng":156.9567,"src":"us","datetime":"2007-04-01 18:39:56","depth":10,"lat":-8.4528},
         {"eqid":"2007hec6","magnitude":7.8,"lng":100.9638,"src":"us","datetime":"2007-09-12 21:49:01","depth":10,"lat":-2.5265}
    ]};

试试这个:

var myData = eval('(' + jsonData + ')');
var firstElement = myData.earthquakes[0];

这是一个很好的参考点:http: //www.json.org/js.html

于 2011-02-15T22:46:54.960 回答