我正在尝试从JSON文件解析值“title,author和ISBN”并将它们存储在名为availableTags
的数组中,但我只得到值undefined
而我不会知道问题所在。
有什么建议吗?
我的代码:
$(document).ready(function () {
var availableTags = [];
$.getJSON( "search.json", function( data ) {
availableTags[0] = data.title;
availableTags[1] = data.author;
availableTags[2] = data.ISBN;
alert(availableTags[0]);
});
});
这是JSON代码
[{"title":"the book","author":"Peter","ISBN":"632764"}]
答案 0 :(得分:2)
您需要注意您的数据变量实际上是一个数组。
您需要将代码更改为:
$(document).ready(function () {
var availableTags = [];
$.getJSON( "search.json", function( data ) {
data = data[0];
availableTags[0] = data.title;
availableTags[1] = data.author;
availableTags[2] = data.ISBN;
alert(availableTags[0]);
});
});
你可能已经错过了支持。
这是一个包含一个项目的数组。
[{"title":"the book","author":"Peter","ISBN":"632764"}]
这是一个项目。
{"title":"the book","author":"Peter","ISBN":"632764"}
答案 1 :(得分:1)
$(document).ready(function () {
var availableTags = [];
$.getJSON( "search.json", function( data ) {
//use data[0] instead of data
var book = data[0];
availableTags[0] = book.title;
availableTags[1] = book.author;
availableTags[2] = book.ISBN;
alert(availableTags[0]);
});
});
答案 2 :(得分:0)
嗯,有点太晚了,但是既然我写了一些东西,也许它对某些人有所帮助:
$(document).ready(function() {
var searchResults = [];
// Assuming data will be something like this
// data = [{"title":"the book","author":"Peter","ISBN":"632764"},{"title":"the other book","author":"Sebastian","ISBN":"123456"}];
$.getJSON("search.json", function(data) {
if (typeof data === 'object' && data.length > 0) {
searchResults = data;
console.info('Referenced to outside variable');
for (var amount = 0; amount < searchResults.length; amount++) {
var result = searchResults[amount];
// do something with each result here
console.group('Search-Result:');
console.log('Title: ', result.title);
console.log('Author: ', result.author);
console.log('ISBN: ', result.ISBN);
console.groupEnd();
}
} else {
console.error('Received wrong data, expecting data to be array');
}
});
});