2011-02-23 83 views
4

我正在試圖解析具有如下所示的確切結構的JSON文件。嘗試使用jQuery解析JSON文件

{ 
    "students": { 
     "student": [ 
      { 
       "id": 1, 
       "name": "John Doe", 
       "image": "pic1.jpg", 
       "homepage": "http: //www.google.com" 
      }, 
      { 
       "id": 2, 
       "name": "Jane Doe", 
       "image": "pic1.jpg", 
       "homepage": "http: //www.google.com" 
      } 
     ] 
    } 
} 

我使用下面的jQuery函數:

function GetStudents(filename) 
{ 
    $.getJSON(filename, function(data){ 
     $.each(data.student, function(i,s){ 
      var id = s.id;; 
      var name = s.name;; 
      var img = s.image;; 
      var homepage = s.homepage; 
      $('.networkTable').append('<tr><td><img src="' + img + '" class="picEven pic" width="33" height="35"></td><td><a href="'+ homepage + '" class="networkLink">' + name + '</a></td></tr>'); 
     }); 
    }); 
} 

有什麼我做錯了嗎?

+2

錯在何處? – 2011-02-23 22:07:31

+4

它應該是'$ .each(data.students.student,...'。這是否有幫助?如果沒有,那麼檢索數據可能會有問題。您是從服務器還是外部讀取文件? – 2011-02-23 22:09:09

+0

data.students? – 2011-02-23 22:10:27

回答

6

您沒有訪問正確的元素。 data不指向students,它指向最外面的元素{students:...}students是它的一個屬性)。該陣列包含在data.students.student

$.each(data.students.student, function() { 
    //... 
}); 

其它注意事項:

  • 你並不需要創建一個局部變量,如果你訪問屬性只有一次(當然它可能更可讀)。

  • 雖然有連續的分號;;是沒有錯的,這是不必要的混亂(至少它讓我困惑;))

1
s.nametry: <br/> 
$("document").ready(function() { 
    $.getJSON(fileUrl, 

    function(data) 
    { 
     $("#div-my-table").text("&lt;table&gt;"); 
     $.each(data, function(i, item) { 
      $("#div-my-table").append("&lt;tr&gt;&lt;td&gt;" + item.prop1 +"&lt;/td&gt;&lt;td&gt;" + item.prop2 + "&lt;/td&gt;&lt;/tr&gt;"); 
     }); 
     $("#div-my-table").append("&lt;/table>"); 
    }); 
}); 
+0

你想用這個代碼演示什麼? – 2011-02-23 22:32:01