Google Shopping API - Jquery + Json - PullRequest
       78

Google Shopping API - Jquery + Json

1 голос
/ 07 октября 2011

Я пытаюсь получить список изображений из Google Shopping и отобразить их на странице.Я использую 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>

JSON-ответ от Google:

{
 "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 секунд, но он не показывает никаких изображений.

Любая помощь была бы полезной.

Спасибо, лорд Снотимус

1 Ответ

2 голосов
/ 07 октября 2011
$.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');
            }
        });
    }
);

Ура! * * 1002

...