2016-01-01 23 views
0

我在本地主機中運行兩個文件(HTML和JSON)並使用$ .getJSON調用JSON文件。JSON數據未顯示

,但不知道爲什麼它沒有顯示在我的表內容

我的HTML文件是:

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script> 
<script> 
    $(function() { 
    var people = []; 

    $.getJSON('people.json', function(data) { 
     $.each(data.feed, function(i, f) { 
      var tblRow = "<tr>" + "<td>" + f.name + "</td>" + "</tr>" 
      $(tblRow).appendTo("#userdata tbody"); 
    }); 
    }); 
}); 
</script> 
</head> 
<body> 
<div class="wrapper"> 
<div class="profile"> 
    <table id= "userdata" border="2"> 
    <thead> 
      <th>First Name</th> 
     </thead> 
     <tbody> 
     </tbody> 
    </table> 
</div> 
</div> 
</body> 
</html> 

和我的JSON文件是:

{ 
    "feed": { 
     "data": [ 
     { 
      "name": "jack", 
      "message": "hello jack", 
     }, 
     { 
      "name": "jack", 
      "message": "hello jack", 
     } 
] 
} 
} 

是Json不正確或HTML文件中的腳本有錯誤?

回答

1

嘗試$.each(data.feed.data,data是從object的關鍵是,當你做你的$。每一個的關鍵feed

0

我相信價值你沒有足夠的水平。你仍然需要遍歷在對象「數據」的項目 - 所以我覺得這是

$.getJSON('people.json', function(data) { 
     $.each(data.feed.data, function(i, f) { 
      var tblRow = "<tr>" + "<td>" + f.name + "</td>" + "</tr>" 
      $(tblRow).appendTo("#userdata tbody"); 
    }); 
    }); 
0

你有2個問題:

1)的JSON是不正確的。請"hello jack"後刪除不必要的逗號:

{ 
    "feed": { 
    "data": [ 
     { 
     "name": "jack", 
     "message": "hello jack" 
     }, 
     { 
     "name": "jack", 
     "message": "hello jack" 
     } 
    ] 
    } 
} 

2)糾正你解析的JSON訪問數據的方式(在$.each()參數更改爲data.feed.data):

<html> 
<head> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script> 
    <script> 
    $(function() { 
     var people = []; 

     $.getJSON('people.json', function(data) { 
     console.log(data); 
     $.each(data.feed.data, function(i, f) { 
      var tblRow = "<tr>" + "<td>" + f.name + "</td>" + "</tr>"; 
      $(tblRow).appendTo("#userdata tbody"); 
     }); 
     }).fail(function(error) { 
     console.error(error); 
     }); 
    }); 
    </script> 
</head> 
<body> 
<div class="wrapper"> 
    <div class="profile"> 
    <table id= "userdata" border="2"> 
     <thead> 
     <th>First Name</th> 
     </thead> 
     <tbody> 
     </tbody> 
    </table> 
    </div> 
</div> 
</body> 
</html> 

3)使用由請求返回的承諾並處理錯誤。這將有助於您在將來更容易地發現這些問題。