Tuesday, March 23, 2010

Bing API 2.0: Consume results as JSON using Javascript

It's pretty easy to consume JSON returned from the Bing API using Javascript. There is one tricky part though.


Browsers don't let you use JSON results from another website due to security restrictions. By dynamically adding a script tag on your page, you can workaround this restriction though. This technique is called JSONP. More information on JSONP can be found on Rick Strahl's blog.

jQuery makes using JSONP relatively easy. The getJSON method does all the hardcore scripting for you. All you need to supply is the url and and a callback function.

The url

In the previous post, we chose the XML format to display our results. We can reuse the url from the previous post, by simply replacing xml.aspx with json.aspx. In this example our url looks like this: http://api.search.live.net/json.aspx?AppId=[YourAppId]&query=Mini+Cooper+S&sources=image

Showing our results

With a little help from our friend jQuery, it's easy to display some results.

When the document is ready, I get the results in a JSON format from the Bing API. I pass in a callback function. This callback function takes the results, loops over the Image results and adds them as an image to a div.

The code looks something like this..

   1:  <html>
   2:  <head>
   3:      <script src="http://code.jquery.com/jquery-latest.js"></script>
   4:      <script type="text/javascript">
   5:          $(document).ready(function(){
   6:              $.getJSON("http://api.search.live.net/json.aspx?AppId=[YourAppId]&query=Mini+Cooper+S&sources=image", 
   7:                  function(data){
   8:                      $.each(data.SearchResponse.Image.Results, function(i, item){                                            
   9:                          $("<img/>").attr("src", item.MediaUrl)                                                                   
  10:                                     .appendTo("#images")
  11:                                     .wrap("<a href='" + item.Url + "'></a>")                                                 
  12:                      });
  13:                  });
  14:          });
  15:      </script>
  16:  </head>
  17:  <body>
  18:      <div id="images"></div>
  19:  </body>
  20:  </html>

And the result looks like this.

Sweet, right?

This post is part of the Bing API 2.0 series.

No comments:

Post a Comment