2016-05-30 17 views
1

JSONファイルから "title、author、ISBN"の値を解析し、availableTagsという配列に格納しようとしていますが、値がundefinedで、どこがわからないのですか問題は。 提案がありますか?getJSON()未定義の値を取得する

マイコード:ここ

$(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"}] 
+2

'data'が配列です。 'data = data [0]'を試してください – Phil

+0

複数の検索エントリがありますか?また、最後に何を達成したいのですか?あなたの目的地はどこですか'? –

答えて

2

です。

あなたがあなたのコードを変更する必要があります:あなたはおそらくsurrondingブラケットを逃した

$(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]); 

}); 
}); 

これは1つの項目を含む配列です。

[{"title":"the book","author":"Peter","ISBN":"632764"}] 

これは1つの項目です。

{"title":"the book","author":"Peter","ISBN":"632764"} 
+1

ありがとうございました:) – user3013745

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]); 

}); 
}); 
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'); 
    } 

    }); 
}); 
関連する問題