从Url获​​取Json数据

时间:2015-11-28 05:03:06

标签: javascript jquery json

我正在尝试使用URL显示来自JSon的数据我收到了未定义的错误。 我正好打电话给json。任何人都可以告诉我为什么我会收到未定义的错误。

这是带有脚本

的HTML文件
    <html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {

            $("#driver").click(function(event){
               $.getJSON('http://localhost:8080/api/organisationUnits.json?fields=:identifiable,coordinates,level,shortName,parent&pageSize=200', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.organisationUnits.name + '</p>');

               });
            });

         });
      </script>
   </head>

   <body>



      <div id = "stage" style = "background-color:#cc0;">
         STAGE
      </div>

      <input type = "button" id = "driver" value = "Load Data" />

   </body>

</html>

这里是JSON中的数据

{"pager":{"page":1,"pageCount":7,"total":1332,"nextPage":"http://localhost:8080/api/organisationUnits?page=2&pageSize=200"},"organisationUnits":[{"lastUpdated":"2015-11-25T18:28:42.912+0000","code":"OU_651071","level":4,"created":"2012-02-17T14:54:39.987+0000","name":"Adonkia CHP","id":"Rp268JB6Ne4","href":"http://localhost:8080/api/organisationUnits/Rp268JB6Ne4","shortName":"Adonkia CHP","parent":{"id":"qtr8GGlm4gg","name":"Rural Western Area","code":"OU_278366","created":"2012-02-17T14:54:39.987+0000","lastUpdated":"2014-11-25T08:37:53.242+0000"}},{"lastUpdated":"2015-11-26T04:28:06.613+0000","code":"OU_278371","level":4,"created":"2012-02-17T14:54:39.987+0000","name":"Afro Arab Clinic","id":"cDw53Ej8rju","href":"http://localhost:8080/api/organisationUnits/cDw53Ej8rju","shortName":"Afro Arab Clinic","parent":{"id":"qtr8GGlm4gg","name":"Rural Western Area","code":"OU_278366","created":"2012-02-17T14:54:39.987+0000","lastUpdated":"2014-11-25T08:37:53.242+0000"}

2 个答案:

答案 0 :(得分:0)

organisationUnits是一个你应该采用第一个索引的数组,如下所示。

jd.organisationUnits[0].name

答案 1 :(得分:0)

首先考虑解析数据。例如

var obj = $.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

http://api.jquery.com/jquery.parsejson/