【发布时间】:2011-07-28 16:05:03
【问题描述】:
我发现了很多和我类似的问题;但我看到的答案似乎都不适合我。所以这是我的问题。我正在使用 jQuery JSONP 来获取有关某些书籍的大量信息(JSON 是静态的,因此它周围有一个硬编码的函数)。我有这个工作得很好。我的问题是我需要多次引用 JSON 并且它是静态的,我想我需要使用这些值设置一个本地数组。下面是我的代码:
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) { });
}
上面代码的 sn-p 所做的是从页面上的某个类别中吐出一个书籍列表。左侧有一个菜单,其中包含类别并触发 changeList() 函数(进而触发其他函数绘制正确的 json 并将它们吐出到页面上)。这部分完美无缺!
这让我想到了我的问题,正如您在 parseResponse() 函数中看到的那样,我正在填充我创建的“bookArray”数组。如果我在函数中引用该数组,我没有问题。但是,如果我尝试在外部引用它(例如 alert(bookArray[0]['title']) 我知道它是未定义的。我做错了什么?我不是最精通技术的人,所以你有对我说小话。感谢您的帮助!
编辑 这是一个 sn-p,可让您了解 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 在上面我的 sn-p 的第 4 行声明。我还没有使用它来测试我尝试使用警报并且它是未定义的。在页面的 HTML 底部,我还尝试了 document.write,但没有成功。
-
我又提出了一个愚蠢的问题。在尝试访问 bookArray 的内容之前,您是否调用了 parseResponse?
-
是的,当我加载 JSON 时会调用 parseResponse。您在上面看到的所有脚本都在我的 HTML 页面的头部。我的测试我试图像我的页脚一样访问。该问题与在函数外部调用有关。好像我在函数内部做 alert(bookArray[0]['title']) 我得到了我所期望的。
标签: javascript jquery arrays function jsonp