使用谷歌图像API

Using Google Images API

本文关键字:API 图像 谷歌      更新时间:2023-09-26

我试图使用谷歌的图像API来搜索图像并将其放入我的html文档中作为div。这就是我到目前为止所拥有的,但似乎没有出现任何东西。这是来自http://code.google.com/apis/imagesearch/v1/devguide.html的零件。这是我第一次使用API,所以我不确定到底发生了什么。

<html> 
  <head> 
    <title>Art Project FTW</title> 
  </head> 
  <body> 
  <br>
  <br>
    <form name="upload" method="post" action="parse_image.php" enctype="multipart/form-data"> 
      <input type="file" name="Image"><br>  
      <input type="submit" value="Upload Image"> 
    </form> 
    <script type="text/javascript" src="https://www.google.com/jsapi?key=xxx"></script>
    <script type="text/javascript" charset="utf-8">
google.load('search', '1');
function searchComplete(searcher) {
  // Check that we got results
  if (searcher.results && searcher.results.length > 0) {
    // Grab our content div, clear it.
    var contentDiv = document.getElementById('content');
    contentDiv.innerHTML = '';
    // Loop through our results, printing them to the page.
    var results = searcher.results;
    for (var i = 0; i < results.length; i++) {
      // For each result write it's title and image to the screen
      var result = results[i];
      var imgContainer = document.createElement('div');
      var title = document.createElement('h2');
      // We use titleNoFormatting so that no HTML tags are left in the title
      title.innerHTML = result.titleNoFormatting;
      var newImg = document.createElement('img');
      // There is also a result.url property which has the escaped version
      newImg.src = result.tbUrl;
      imgContainer.appendChild(title);
      imgContainer.appendChild(newImg);
      // Put our title + image in the content
      contentDiv.appendChild(imgContainer);
    }
  }
}
function onload() {
  // Our ImageSearch instance.
  var imageSearch = new google.search.ImageSearch();
  // Restrict to extra large images only
  imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                             google.search.ImageSearch.IMAGESIZE_MEDIUM);
  // Here we set a callback so that anytime a search is executed, it will call
  // the searchComplete function and pass it our ImageSearch searcher.
  // When a search completes, our ImageSearch object is automatically
  // populated with the results.
  imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);
  // Find me a beautiful car.
  imageSearch.execute("Subaru STI");
}
google.setonloadCallback(onload);​
</script>
  </body>
</html>

提前感谢!

它不能工作,因为你正在寻找一个具有ID='content'的HTMLElement,你没有任何具有该ID的元素

试着把你的js函数放在<head></head>