2012-11-02 160 views
0

我有一個數據對象,裏面,我有數據對象與json數據裏面。這是怎麼樣的。該文件的名稱是​​無法讀取JSON數據使用jQuery與循環

var data = 
[ 
{ 
    title: 'this is title one', 
    commit: 'this is commit' 
}, 
{ 
    title: 'this is title two', 
    commit: 'this is commit' 
}, 
{ 
    title: 'this is title three', 
    commit: 'this is commit' 
}, 
{ 
    title: 'this is title four', 
    commit: 'this is commit' 
}, 
{ 
    title: 'this is title five', 
    commit: 'this is commit' 
}, 
{ 
    title: 'this is title six', 
    commit: 'this is commit' 
}, 
{ 
    title: 'this is title seven', 
    commit: 'this is commit' 
} 
] 

這裏是我的代碼

for (var i = 0; i < data.length; i++) { 
       $(container).load(view, function() { 
        console.log(data[i].title); 
        li.append('<img src="../images/profile.png" alt="Profile photo" />'); 
        li.append('<span class="commit">' + data[i].title + '</span>'); 
        li.append('<p><a href="#" class="comment">' + data.commit + '</a></p>'); 
        li.append('<section class="clear"></section>'); 
        $('#home ul').append(li); 
       }); 
      } 

現在我在我的控制檯收到此錯誤

Cannot read property 'title' of undefined 

上面的錯誤是在這條線

li.append('<span class="commit">' + data[i].title + '</span>'); 

如何解決這個問題?

回答

0

那麼,data.js不是真的json。從負載()

首先切換到的getJSON()

$.getJSON(view, function(data) { }) 

下刪除行

var data = 

只是有JSON內容。 jQuery將分配JSON給參數數據。

0

你的json數組包含錯誤。

您可以驗證您的JSON這裏http://json.parser.online.fr/

必須是這樣:

{ 
"title": ["this is title one", "this is title two", "this is title three", "this is title four", "this is title five", "this is title six", "this is title seven" ] 
, 
"commit": [ "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit" ] 
}