使用phonegap和jQueryMobile的JQuery $ .ajax Google Books API

时间:2013-05-31 17:58:47

标签: javascript jquery jquery-mobile google-api

如何使这段代码工作,问题是我似乎无法访问返回的数据,我知道它连接到服务器,但是因为某些原因它不会工作,例如,我试过提取标题但没有出现。

$.ajax({
        url : "https://www.googleapis.com/books/v1/volumes?q=harry+potter",
        dataType : "jsonp",
        async : true,
        //if ajax call succeeds perform this action
        success : function(result) {
            ajax.parseJSONP(result);
        },
        //if there is an error to the ajax call perform this action
        error : function(request, error) {
            alert('Network error has occurred please try again!');
        }
    });
    //parseJsonP and add new elements to list-view 
    var ajax = {
        parseJSONP : function(result) {
            //iterate each returned item 
            $.each(result, function(i, row) {
                $('#listview_test').append('<li><h3>' + row.volumeInfo.title + '</h3></a></li>');
            }); //end iteration of data returned from server and append to the list
            $('#listview_test').listview('refresh'); // refresh the list-view so new elements are added to the DOM
        }
    }

我的混淆是在回调方法上,在他们的示例中,Books API有一个如下所示的代码,但是我没有得到它的这一部分q=harry+potter&callback=handleResponse,我怎么能在使用$ .ajax方法时做到这一点。尝试了解所有的部分,但仍然非常混乱?

<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>

1 个答案:

答案 0 :(得分:2)

尝试替换以下代码:

$.each(result, function(i, row) {

这个:

$.each(result.items, function(i, row) {

根据Google示例代码,数据位于返回对象中名为items的数组中。