您现在的位置: IT专家网 > Web服务子站 > WebService开发
使用Google Ajax Search API
发出异步请求并不意味着只是与您自己的服务器端程序交互。其实也可以与一些公共API,例如来自Google或Amazon的API进行通信,从而为Web应用程序增加您自己的脚本和服务器端程序所不能提供的更多功能。在本文中,Brett McLaughlin教您如何向公共API,例如Google提供的API发出请求并接收其响应。

图1. 登记使用Google的Ajax Search API
阅读完协议并勾选了复选框之后,输入URL,单击Generate API Key,等待一二秒钟。此时必须登录Google,或者创建一个帐户。这是一个相当标准的过程,您应该可以自己完成。完成上述操作后,可以看到一个回复页面,其中给出了一个非常长的密钥,并确认您的URL,甚至还给出一个示例页面。这个密钥看上去类似于以下形式:
ABQIAAAAjtuhyCXrSHOFSz7zK0f8phSA9fWLQO3TbB2M9BRePlYkXeAu8lHeUgfgRs0eIWUaXg
Google的API文档
在开始使用获得的密钥之前,要花点时间阅读一下Google的API文档(在提供密钥的页面的底端有一个链接,本文的参考资料中也提供了该链接)。即使您通过本文有了很好的初步认识,仍然会发现Google的API文档是一个很好的参考资料,通过该文档可能会得到关于如何在您自己特有的应用程序中、站点上使用Google的一些有趣的想法。
最简单的Google搜索Web应用程序
为了看看实际效果,我们以Google提供的示例Web页面为例,对它稍做修改,然后看看它会变成什么样子。
创建搜索框
清单1显示了一个很简单的Web页面。将这段代码输入到您喜欢使用的编辑器中,保存为文件,然后将该文件上传到上个小节中提供给Google的域或URL上。
清单1. 一个简单的Google搜索应用程序的HTML代码
| < html>
< head> < title>My Google AJAX Search API Application < link href="http://www.google.com/uds/css/gsearch.css" type="text/css" rel="stylesheet" /> < script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key= YOUR KEY HERE " type="text/javascript"> < /script> < script language="Javascript" type="text/javascript"> function OnLoad() { // create the Google search control var searchControl = new GSearchControl(); // These allow you to customize what appears in the search results var localSearch = new GlocalSearch(); searchControl.addSearcher(localSearch); searchControl.addSearcher(new GwebSearch()); searchControl.addSearcher(new GvideoSearch()); searchControl.addSearcher(new GblogSearch()); // Tell Google your location to base searches around localSearch.setCenterPoint("Dallas, TX"); // "Draw" the control on the HTML form searchControl.draw(document.getElementById("searchcontrol")); } < /script> < /head> < body onload="OnLoad()"> < div id="searchcontrol" /> < /body> < /html> |
- 本文关键词:

