2013-05-31 53 views
2

閱讀Google Books API後,他們獲得了關於如何使用REST API的documentation,並且他們還提到了將API與客戶端javascript一起使用。使用jQuery .ajax和jQueryMobile從Google Books API獲取JSONP示例

我正在製作phonegap/JQueryMobile應用程序,並且我想使用ajax和Google Books API獲取數據,但是他們的API很難讓我理解。

我想要獲取的是使用$ .ajax方法的JSONP對象。

您是否有任何示例代碼,它使用Google Books API獲取數據,並使用jQuery $ .ajax在phonegap應用程序中工作。

我必須excplicity提供回調方法,還是我去了這一點,僅僅是混亂...

在此代碼:

<body> 
    <div id="content"></div> 
    <script> 
     function handleResponse(response) { 
     for (var i = 0; i < response.items.length; i++) { 
     var item = response.items[i]; 
     // in production code, item.text should have the HTML entities escaped. 
     document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title; 
     } 
    } 
    </script> 
    <script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script> 
    </body> 

從谷歌圖書API他們說你可以得到JSONP數據,但我似乎無法掌握如何使用jQuery $ .ajax和使用jsonp作爲類型。

回答

3

只是爲了讓你開始,你可以這樣做:

// Set the api variable 
var googleAPI = "https://www.googleapis.com/books/v1/volumes?q=harry+potter"; 

// Make a ajax call to get the json data as response. 
$.getJSON(googleAPI, function (response) { 

    // In console, you can see the response objects 
    console.log("JSON Data: " + response.items); 

    // Loop through all the items one-by-one 
    for (var i = 0; i < response.items.length; i++) { 

     // set the item from the response object 
     var item = response.items[i]; 

     // Set the book title in the div 
     document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title; 
     } 
}); 

FIDDLE DEMO

+0

HEJ感謝您的例子。我有問題讓我感到困惑,因爲我最近很難理解Java腳本。你使用一個匿名函數,並帶有一個參數'response',你現在將如何增加這個參數,我主要是一個java的經驗,這種調用方法對我來說很困惑。如果我想根據用戶輸入添加API密鑰和動態值,那麼您在此代碼中將更改什麼? –

+0

實際上,匿名函數是一個回調函數,如果請求成功則執行該函數。成功回調會傳遞返回的數據,這些數據通常是JSON結構定義的JavaScript對象或數組,並使用$ .parseJSON()方法進行分析。它也傳遞了響應的文本狀態。你可以找到更多關於它的信息[這裏](http://api.jquery.com/jQuery.getJSON/) –

+0

所以我看到的論點,實際上是返回的數據,它花了我很長一段時間才終於掌握了這個概念, 這次真是萬分感謝。有一個問題,他們的代碼與他們的示例有什麼不同,他們使用帶回調方法的鏈接:src =「https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse」 '例如,你不是在URL的末尾添加回調嗎? –