2013-05-31 23 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的末尾添加回调吗? –