【问题标题】:Google Shopping API - Jquery + Json谷歌购物 API - Jquery + Json
【发布时间】:2011-10-07 15:03:23
【问题描述】:

我正在尝试从 Google 购物中检索图片列表并将其显示在页面上。我使用的是 Jquery 和 Json,而不是 atom。

我正在使用以下代码,该代码改编自类似的 Flickr 示例。

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("https://www.googleapis.com/shopping/search/v1/public/products?callback=?",
  {
    key: "blocked out for stackoverflow", 
    country: "US", 
    q: "mp3 player", 
    alt: "json" 
  },
  function(data) {

 $.each(data.items, function(i, item){
   var img = $("<img/>").attr("src", item.images.link);
   $("<a/>").attr({href: item.images.link, title: "Courtesy of Flicker"})
      .append(img).appendTo("#images");
});
  });</script>

</body>
</html>

来自 Google 的 JSON 响应:

{
 "kind": "shopping#products",
 "etag": "\"OyT1ifyoCQdoaDfBnjJePyCaGZI/CzI9J98veA7dKdf7KRl5ITkHylw\"",
 "id": "tag:google.com,2010:shopping/products",
 "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=digital+camera&alt=json&startIndex=1&maxResults=25",
 "nextLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=digital+camera&alt=json&startIndex=26&maxResults=25",
 "totalItems": 822804,
 "startIndex": 1,
 "itemsPerPage": 25,
 "currentItemCount": 25,
 "items": [
  {
   "kind": "shopping#product",
   "id": "tag:google.com,2010:shopping/products/1172711/16734419455721334073",
   "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/1172711/gid/16734419455721334073?alt=json",
   "product": {
    "googleId": "16734419455721334073",
    "author": {
     "name": "B&H Photo-Video-Audio",
     "accountId": "1172711"
    },
    "creationTime": "2011-04-23T22:17:32.000Z",
    "modificationTime": "2011-10-06T02:20:27.000Z",
    "country": "US",
    "language": "en",
    "title": "Canon powershot sx30 is digital camera 4344B001",
    "description": "Canon's PowerShot SX30 IS Digital Camera raises the bar for optical zoom lenses--way way up. This ladies and gentlemen is a 35x 24-840mm equivalent zoom lens taking you from a true wide-angle to an ultra telephoto suitable for wildlife and sports photography and who knows maybe even pictures of the stars (just kidding about the astronomy pix kids). And it comes with Canon's Optical Image Stabilizer so you'll be able to capture great shots even at super telephoto focal lengths without unseemly camera shake. A Zoom Framing Assist makes it easy to follow a moving subject even using the super telephoto. The lens uses a double-sided aspherical glass-molded lens an ultra-high refraction index lens enhanced negative refractive power and UD glass to correct wide-angle distortion and suppress chromatic aberration. With 14.1MP you'll get high resolution pictures whether you're shooting landscapes pictures of the kids or those 2 blue herons on the other side of the lake. The high resolution 2.7 Vari-Angle display screen makes it easy to frame and playback your photos and video--that's right you also get gorgeous 720p HD video which can be shot using image stabilization and full zoom with stereo sound. There's also Advanced Smart AUTO which recognizes and sets optimal settings for 23 pre-defined shooting situations. Canon's proprietary DIGIC 4 Image Processor delivers faster more accurate noise reduction for better image quality even at high ISO ratings. This little beauty is ready to go out and play. 4344B001 PowerShot SX30 IS Digital Camera Feature Highlights: PowerShot SX30 IS Digital Camera, 35x Zoom Lens (24-840mm Equivalent), Zoom Framing Assist for Telephoto Photos, 14.1MP High Resolution, 2.7\" Wide Vari-angle LCD Display, 720p HD Video With Stereo Sound, Use Stabilization & Zoom for Video, Advanced Smart AUTO for 23 Situations, Optical Image Stabilizer for Sharp Pix, Powerful DIGIC 4 Image Processor, Lithium-ion Rechargeable Batteries",
    "link": "http://www.bhphotovideo.com/c/product/734782-REG/Canon_4344B001_PowerShot_SX30_IS_Digital.html/BI/1239/kw/CAPSSX30",
    "brand": "Canon",
    "condition": "new",
    "gtin": "00013803127348",
    "gtins": [
     "00013803127348"
    ],
    "inventories": [
     {
      "channel": "online",
      "availability": "inStock",
      "price": 399.95,
      "shipping": 0.0,
      "currency": "USD"
     }
    ],
    "images": [
     {
      "link": "http://www.bhphotovideo.com/images/images345x345/734782.jpg"
     }
    ]
   }
  },

它正在加载,我可以看到处理 JSON 响应大约需要 4 秒,但它没有显示任何图片。

任何帮助都会很棒。

谢谢, 斯努蒂姆斯勋爵

【问题讨论】:

  • 如果您 alert(item.images.link); 是否正确输出您预期的 URL?你有&lt;div id="images"&gt;&lt;/div&gt; 标签吗?
  • 尝试了警报,它没有输出链接。我确实有图像 div 标签。
  • 在 Chrome 中打开控制台,得到:未捕获的类型错误:无法读取未定义的属性“链接”
  • 如果 item.images.link 为空,那么这表明您没有正确地将代码指向正确的 JSON 节点。如果您可以发布有用的 JSON 响应。
  • 好的,我会编辑我原来的帖子。

标签: jquery json api google-shopping-api


【解决方案1】:
$.getJSON(
    'https://www.googleapis.com/shopping/search/v1/public/products?callback=?',
    {
        key     : 'redacted', 
        country : 'US', 
        q       : 'mp3 player', 
        alt     : 'json' 
    },
    function(data)
    {
        $.each(data.items, function(i, item)
        {
            if (item.product.images.length > 0) // sanity check
            {
                var link = item.product.images[0]['link']; // cache value
                var img  = $('<img/>').attr('src', link);
                $('<a/>')
                    .attr({
                        href  : link,
                        title : 'Courtesy of Flicker'
                    })
                    .append(img)
                    .appendTo('#images');
            }
        });
    }
);

干杯!

【讨论】:

  • 英雄。这行得通。最后我知道这是一个层次结构问题,因为我检查了 Chrome 的网络选项卡,它返回了 JSON 负载,只是无法选择图像。是否有教程或简单的方法来解决如何在 JSON 响应中选择正确的对象?
  • 嘿。我只是使用console.log(data) 作为检查响应的一种方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多