Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using the Yahoo! Web Service

<script language="JavaScript" type="text/javascript"
  src="http://api.search.yahoo.com/WebSearchService/
V1/webSearch?appid=XXXXX&query=JavaScript&output=
json&callback=showResults">
</script>

More and more Web Services provide a JSON interface, and among the first ones to do so were the Yahoo! Web Services. After a (free) registration at http://api.search.yahoo.com/webservices/register_application, you get your personal application ID. This ID is tied to your application and must be used instead of the XXXXX placeholder in this phrase. Then, the preceding <script> tag not only calls the Web Service and expects JSON back, but also provides the name of a callback function that is called after the data is there. So your application receives JavaScript code from the Yahoo! server and executes it—which means you have to trust Yahoo! in order to use it. Then, the callback function gets a JavaScript object with the Yahoo! search results.

The following code then creates a bulleted list with the data from the Web Service. More information about the specific format of the data returned from Yahoo! can be found at the online documentation at http://developer.yahoo.com/search/web/V1/webSearch.html. Figure 11.6 shows the output of this code.

Calling the Yahoo! Web Service with JavaScript (yahoowebservice.html)

<script language="JavaScript"
  type="text/javascript">
function showResults(data) {
  var ul = document.getElementById("output");
  for (var i=0; i < data.ResultSet.Result.length; i++) {
    var text = document.createTextNode(
      data.ResultSet.Result[i].Title + " - " +
      data.ResultSet.Result[i].Url);
    var li = document.createElement("li");
    li.appendChild(text);
    ul.appendChild(li);
  }
}
</script>
<body>
  <p><ul id="output"></ul></p>
</body>
<script language="JavaScript" type="text/javascript"
  src="http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=XXXXX&query=JavaScript&output=json&callback=showResults">
</script>
Figure 11.6

Figure 11.6 The Yahoo! search results.

  • + Share This
  • 🔖 Save To Your Account