4

Google Books API を使用して書籍のリストを取得していますが、一部の書籍エントリにAuthorsなどのキー/プロパティがない場合や、 Thumbnailがない場合があります。したがって、JavaScript は、アクセスしようとしているプロパティが未定義であり、アプリケーションが動かなくなったと言っています。

キーワーク Java を含む書籍検索からの Json データの例

フルリンク

https://www.googleapis.com/books/v1/volumes?q=java&callback=jQuery191020691258599981666_1377508821982&_=1377508821983

例: Authorsが欠落している場合

TypeError: row.volumeInfo.authors is undefined

私は提案された2つの解決策を試しました

if ( typeof (authors) != "undefined"){}

if('authors' in booksObject) {}

しかし、このプロパティが存在する場合でもループに入らないため、それらのどれも機能していないようです。

これは私が呼び出す場所です

function populateListview(books) {

//iterate each returned item
$.each(books.items, function(i, row) {

    //populate each row in the list
    var htmlString = '<li><a href="book_details.html?id=' + row.id + '"><img src="';

    htmlString += row.volumeInfo.imageLinks.thumbnail + '"';
    htmlString += 'class="ui-li-has-thumb"/><h3>';
    //Check if authors exists in JSON
    htmlString += row.volumeInfo.title + '</h3><p>' + row.volumeInfo.authors[0] + '</p></a></li>';

    //If not add an undefined authors string in the authors 


    console.log(htmlString);

    //append new html to the list
    $('#book_list').append(htmlString);
});

$('#book_list').listview('refresh');
// refresh the list-view so new elements are added to the DOM
};
4

3 に答える 3

1

確認してもいい$.isArray(row.volumeInfo.authors) && row.volumeInfo.authors.length > 0

console.log(books.toString());
// iterate each returned item
$.each(books.items, function(i, row) {

    // populate each row in the list
    var htmlString = '<li><a href="book_details.html?id=' + row.id
            + '"><img src="';

    htmlString += row.volumeInfo.imageLinks.thumbnail + '"';
    htmlString += 'class="ui-li-has-thumb"/><h3>';
    if ($.isArray(row.volumeInfo.authors) && row.volumeInfo.authors.length > 0) {
        // code for what to do with json here
        htmlString += row.volumeInfo.title + '</h3><p>'
                + row.volumeInfo.authors[0] + '</p></a></li>';
    } else {
        htmlString += row.volumeInfo.title + '</h3><p>' + "Author Undifined"
                + '</p></a></li>';
    }

    console.log(htmlString);

    // append new html to the list
    $('#book_list').append(htmlString);
});

$('#book_list').listview('refresh');
// refresh the list-view so new elements are added to the DOM
于 2013-08-26T09:10:40.603 に答える
1

これを試して :

if(booksObject.image) {
 //do stuff with it
 } else if( booksObject.author ) {
 //do stuff with author
 }
于 2013-08-26T09:19:25.223 に答える
0

JSON にキーまたは値が存在するかどうかを確認する非常に簡単な方法を次に示します。

var jsonString = JSON.stringify(yourJSON);

if (jsonString .indexOf("yourKeyOrValue") > -1){
    console.log("your key or value exists!");
}

それは速く、簡単で、簡単です。

于 2014-06-11T13:49:24.367 に答える