我花了數小時尋找使用JS讀取JSON文件。 我發現的最接近的是這https://gist.github.com/zuch/6224600。從文件中讀取後無法訪問JSON內容
cells.json:
{
"cells": [
{
"img": "img/singlestitch_thumb.jpg",
"url": "http://www.google.com",
"description": "an interactive 'kite' sketch based on a favorite letter[requires java]",
"smallwin": true
},
{
"img": "img/text3d_thumb2.jpg",
"url": "http://www.yahoo.com",
"description": "animated custom font design in 3d (featured on the 'processing' site)[requires java]",
"smallwin": true
},
{
"img": "img/jazzer_thumb.jpg",
"url": "http://flickr.com",
"description": "a 3d musician that 'plays along' with arbitrary audio tracks[req. javajsyn]",
"smallwin": true
}
]
}
testjson.html:
var cells = [];
$.getJSON("cells.json", function(json) {
$.each(json, function(i, lv_1) {
$.each(lv_1, function(j, lv_2) {
$.each(lv_2, function(k, lv_3) {
//console.log(k + ':' + lv_3 + '');
//console.log(JSON.parse(k + ':' + lv_3 + ''));
cells.push(k + ':' + lv_3 + '');
});
});
});
});
console.log(cells);
這是錯誤。
console.log(cells[0].url); // TypeError: cells[0] is undefined
我無法訪問其中的元素。
附件是zip文件包。您可以使用Firefox或設置本地服務器進行測試。 https://www.dropbox.com/s/nmfq98s7raep92r/json%20test.zip?dl=0
謝謝!
http://jsfiddle.net/Lnjg57t8/錯誤:未定義 – 2014-12-02 12:28:30
這是從來沒有去上班的你創建一個數組,而不是一個對象。如果你想要一個對象,你需要徹底改變你的邏輯 – 2014-12-02 12:28:52
謝謝!有沒有教程呢?或者什麼是閱讀它的最佳方式?我只想讀第一個'url',第一個'img',然後是第二個,等等。 – 2014-12-02 12:30:26