我發現了很多類似於我的問題;但我看到的所有答案似乎都不適合我。所以這是我的問題。我正在使用jQuery JSONP獲取有關某些書籍的很多信息(JSON是靜態的,因此它包含了一個硬編碼函數)。我有這個偉大的工作。我的問題是我需要多次引用JSON,並且它是靜態的,我想我需要使用這些值設置本地數組。因此,這裏是我下面的代碼:JSONP數組undefined功能之外undefined
function changeList(cat) {
getList(cat);
}
var bookArray = new Array();
function parseResponse(jsonData) {
$('#bookList').empty();
var items = [];
var p = '0';
$.each(jsonData, function(item, i) {
bookArray[p] = { 'bookId':i.bookId, 'category':i.category, 'publishedDate':i.publishedDate, 'title':i.title, 'description':i.description, 'images':i.images };
var allImages = i.images;
if(allImages.length > 1) {
var imageLoc = allImages.toString().split(",");
} else {
var imageLoc = new Array(allImages);
}
var theDate = new Date();
theDate.setTime(i.publishedDate * 1000);
var year = theDate.getUTCFullYear();
var month = theDate.getUTCMonth();
var day = theDate.getUTCDate();
var d = months[month] + " " + day + ", " + year;
items.push('<li><a href="/' + i.category + '/' + i.bookId + '/index.html"><img border="0" height="70" width="124" src="' + imageLoc[0] + '"><p>Published: <strong>' + d + '</strong><br /><span class="bookTitle">' + i.title + '</span> ' + i.description + '</p></a></li>');
p++;
});
$('<ul/>', {
html: items.join('')
}).appendTo('#bookList');
}
function getList(section) {
$.getJSON('http://www.otherdomain.com/book_'+ section +'.json?format=jsonp&callback=?', function(data) { });
}
什麼上面的代碼片斷的作用是從頁面上某cateogry吐出來的書單。在左側有一個菜單,它具有類別並激發changeList()函數(這又會觸發其他函數來繪製正確的json並將其吐出頁面)。這部分工作完美無瑕!
這引起我的問題,你可以在parseResponse()函數中看到我填充了我創建的'bookArray'數組。如果我在函數內引用該數組,我沒有任何問題。然而,如果我試圖在外面引用它(例如alert(bookArray [0] ['title']),我會發現它是未定義的。我做錯了什麼?我不是最科技的薩維人,所以你有使用小詞對我感謝所有幫助
編輯 這裏是一個片段給你什麼樣的JSON文件看起來像一個想法:!
parseResponse(
[{
"bookId":"1",
"category":"A",
"publishedDate":"1266870137",
"title":"Title to first story",
"description":"The first story.",
"images":["http://www.otherdomian.com/books/fff.jpg","http://www.otherdomian.com/books/aaa.jpg"]
},{
"bookId":"2",
"category":"A",
"publishedDate":"1366870142",
"title":"Title to second story",
"description":"The second story.",
"images":["http://www.otherdomian.com/books/fff.jpg","http://www.otherdomian.com/books/aaa.jpg"]
}
])
你是否聲明var bookArray的某處?它在哪裏被使用,它是未定義的。我說得對,這是可擴展範圍的問題,而不是你的json? –
bookArray在我上面的代碼片段的第4行中聲明。我還沒有用它來測試我試圖使用警報,它是未定義的。在頁面的HTML底部,我也嘗試了一個沒有運氣的document.write。 – Dusty
來自我的一個更愚蠢的問題。在嘗試訪問bookArray的內容之前,您是否調用過parseResponse? –