2016-08-24 67 views
0

我想检索标题,作者从https://www.googleapis.com/books/v1/volumes?q=isbn:9780439023528在JavaScript和结果显示在HTML中。如何从Google book api url中检索数据?

HTML:

<p id="demo"></p> 

JAVASCRIPT:

function getBookDetails(isbn) { 
     isbn = "9780439023528"; 
     var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn; 
     var response = UrlFetchApp.fetch(url); 
     var results = JSON.parse(response); 

     if (results.totalItems) { 
      var book = results.items[0]; 
      var title = (book["volumeInfo"]["title"]); 
      document.getElementById("demo").innerHTML = book; 
     } 
    } 
}); 
+0

此网址无法正常重定向 – msvairam

+0

我添加一些代码先生 – Lisa

+0

https://www.googleapis.com/books/v1/volumes?q=isbn:9780439023528该网址无法正常运作 – msvairam

回答

0

UrlFetchApp类不在客户端JavaScript可用,这是它看起来像你正在尝试做的。您只能在服务器端的Google Apps Script .gs文件中使用它。

但是,您可以使用XMLHttpRequest来解决您的问题。

function getBookDetails(isbn) { 
    isbn = "9780439023528"; 
    var xmlhttp = new XMLHttpRequest(); 
    var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn; 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      var x = JSON.parse(xmlhttp.responseText); 
      callback(x); 
     } 
    }; 
    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
} 
function callback(x) { 
    //do things with your data here 
    console.log(x); 
} 
+0

如何显示书名? – Lisa