9 of the Ajax Learning Series: using the Google Ajax search API

Source: Internet
Author: User

Sending an asynchronous request does not mean that it only interacts with your own server program. In fact
API, such as an API from Google or Amazon
Applications add more features that your scripts and server programs cannot provide. In this article, Brett McLaughlin teaches you how to send requests to public APIs, such as the APIS provided by Google, and receive their responses.
So far, this series only involves sending requests from client web pages to server scripts and programs. This is how Ajax applications (asynchronous Web applications that use XMLHttpRequest objects) work between 80% and 90%. However, this method has serious limitations: You will be limited by your talents and programming skills, even if not, at least, it is limited by the talents and programming skills of programmers in the company team.

Sometimes, you really want to implement some functions, but you do not have the technical knowledge you need to achieve this goal. This is almost always the case. Maybe you don't know some syntaxes or how to find the appropriate algorithms. Sometimes, you may not have data or resources (human resources or data resources) that meet your needs ). In these cases, you may think, "Alas, how nice it would be if I could use other people's code! "This article aims to solve this problem.

Open source scripts and programs

Before discussing the actual content of this article (using public APIs in Web applications), it is necessary to talk about open source scripts and programs. To put it simply, open source code is a term used to describe code that can be used and reused in your own applications to a certain extent for free. In short, you can get the open source code written by someone else and put it into your own environment without having to pay for it or being limited by (a lot.

If open source code is used, you may need to add additional documents for the application, or report your changes to the open source code program or script to the community. No matter how you use this program, the final result is that you can use this piece of code: you do not have to write it yourself, or, without a lot of help and resources, you cannot write the code, but you do not have these resources at hand. Projects such as Apache provide convenience for others' work-don't worry, they want you to use their work!

Online articles and tutorials

It would be silly to post articles on w3club without mentioning a large number of references such as articles, tutorials, and white papers on the Internet. There are hundreds of teaching materials on the Internet, and you may find nearly a thousand Ajax articles-I have published nearly 10 articles in this series! Most of these articles have available code, examples, downloads, and other types of resources.

If you are unable to write the server-side programs or scripts you want to use, or you cannot find the required open source code programs or scripts, you can open the Google website, try to enter a basic description of the content to be found. Then perform the same operation on the developerworks website. You can often find the required code, even the entire script, and some helpful comments and descriptions about how it works.

Use public APIs

In many cases, you may encounter non-technical issues. You can write a script or code segment without any help, but you do not have the data or resources you need at hand. In these cases, even with tutorials or open source code scripts, more things are needed. For example, consider adding a search engine to a Web page. The premise is that you already have the data you want to search for-but what if you want to search for data outside your company or organization?

If it is not because of technical reasons, but because of data restrictions, a public API may help you solve the problem. Public APIs allow the use of programs on other people's servers and other people's data. Generally, the API only defines how to interact with the program. For example, a search request can be sent through a public API for Google search engine, but Google Code searches for Google data and returns the result to your program. You can not only use others' skills in writing these programs, but also use data that far exceeds your company's support.

Preparations for using the Google Ajax search API

Undoubtedly, Google is still an extremely important application in the online age. When I got to my grandmother and got to my 4-year-old, I knew Google even if I didn't understand what was going on the Internet. It's not surprising that Google is running so popular and useful search engines and is committed to providing (almost all) free services, it provides public APIs that can be used in your own programs. In this section, you will complete the preparation for using Google APIs and have a clear understanding of how to perform asynchronous application sessions with Google.

Get developer keys from Google

This article focuses on Google's Ajax search API. Visit the Google Ajax search API homepage (1) to find more information about this API.

Figure 1. Google's Ajax search API page

The first step is to click the sign up for a Google Ajax search API key link. This will go to another page where you can register to use this Google API. You need to accept all terms of use (I believe that all terms are not malicious) and provide the URL of the Web site where your application is located (2 ).

Figure 2. register and use Google's Ajax search API

What URL should I use?

The URL requested by Google is roughly the domain of the site. If you have your own domain, just like me, you can use
Http://www.newinstance.com (of course, replace my domain with your own domain ). You must specify a more detailed URL only when the site uses a subdomain or a specific path in a large domain. In this case, you may need to use shapes such as http://www.earthlink.net /~ Bmclaugh or http://brett.earthlink.net
Such a URL. However, in addition to the above special circumstances, do not provide Google with a URL that is too detailed-you only need to provide the root URL used to access the entire web site, you can use this API everywhere in this URL.

After reading the protocol and selecting the check box, enter the URL and click Generate API key. Wait for one or two seconds. You must log on to Google or create an account. This is a fairly standard process, and you should be able to do it yourself. After completing the preceding operations, you can see a reply page, which provides a very long key, confirms your URL, and even provides a Sample Page. This key looks like the following:
Bytes

Google API documentation

Before you start using the obtained key, take some time to read Google's API documentation (there is a link at the bottom of the page that provides the key, which is also provided in the references in this article ). Even if you have a good preliminary understanding of this article, you will still find that Google's API documentation is a good reference, this document may give you some interesting ideas about how to use Google in your own applications and websites.

The simplest Google search Web Application

In order to see the actual results, we take the example web page provided by Google as an example to make a slight modification to it and then see what it will look like.

Create search box

Listing 1 shows a simple web page. Enter this code in your favorite editor, save it as a file, and upload the file to the domain or URL provided to Google in the previous section.

Listing 1. A simple Google search application's HTML code


<HTML>
<Head>
<Title> my Google Ajax search API application </title>
<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>

Note: Use the key obtained from Google to replace the bold text in the code. When loading this page, you can see a page similar to figure 3.


Figure 3. The simplest Google search form

This page looks very simple, but in fact the little control is behind Google's powerful search capabilities.

Run search

Enter a search term and click search to start Google. You can quickly see some search results, as shown in figure 4.

Figure 4. Google search results

Add pre-search page

Obviously, after a search, the page looks much better. Video, blog, and search results make the page more beautiful. Therefore, you may want to add a pre-search, that is, a search term you define. When you load your page, you will first see the search results of the search term. To do this, add the line of code shown in bold in Listing 2 to JavaScript.

Listing 2. Add a pre-search term

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 "));

Searchcontrol.exe cute ("Christmas Eve ");
}

Obviously, you can add your initial search term to the Code to customize the content displayed during page loading.

Javascript Parsing

Before proceeding, let's take a look at the functions of these basic commands. First, create a new gsearchcontrol, as shown in listing 3. The following structure can be used to execute all search tasks:

Listing 3. Creating a New gsearchcontrol

Function onload (){
// Create the Google search control
VaR searchcontrol = new gsearchcontrol ();

...
}

Next, the Code uses glocalsearch to set a new local search. This is a special Google structure that allows you to perform a search for a specific location. This local search is shown in Listing 4.

Listing 4. Set a new local search

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 ();
...

// Tell Google your location to base Searches around
Localsearch. setcenterpoint ("Dallas, TX ");

...
}

As long as you know the object and method calls, the above Code does not need to be explained. The code in Listing 4 creates a new local searcher and sets the central location of the search.

The lines in listing 5 tell the search control what type of search should be performed.

Listing 5. Allowed search types

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 ");

...
}

Most of the search types can be viewed. The following is a brief summary:

1. gwebsearch: This object is used to search for the Web. It is the most famous search type of Google.
2. gvideosearch: This object searches for videos related to search terms.
3. gblogsearch: This object is used to search for a blog. The structure and tag of the blog are different from those of other web content types.
You have learned how to pre-load a specific search. Then, only the draw () method is called, as shown in Listing 6. You provide
Dom element (for more information about Dom, see the previous articles in this series in references ). Then, this control appears magically on the form for users to use.

Listing 6. Drawing search controls

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 "));

Searchcontrol.exe cute ("Christmas Eve ");
}

Where is Ajax?

So far, it cannot be clearly seen where there is Asynchronization in this simple search box. Of course, it is great to provide a Google search box somewhere in a web application, but it is a series of articles about Ajax applications, not a series of articles about Google search. So where exactly is Ajax?

Enter the search term and click the search button. You will notice a very Ajax-style response: the search results are displayed directly, and there is no page re-loading process. This is one of the symbols of most Ajax applications, that is, content changes are directly displayed without reloading the page. Obviously, this is beyond the capacity range of the conventional request/response model. But where is XMLHttpRequest? What are the instant request objects in so many articles? Besides the getelementbyid () method, where are Dom and page operations? In fact, all of this is included in
Two lines of code in HTML.

Google handles JavaScript

The code to be noted in the first line has not been discussed in detail, as shown in listing 7.

Listing 7. Critical JavaScript files

<Script
Src = "http://www.google.com/uds/api? File = UDS. JS & V = 1.0 & Key = [your Google key]"
Type = "text/JavaScript"> </SCRIPT>

The syntax here is not particularly worth noting, but it should be noted that Google stores a file named UDS. JS, which contains all the Javascript needed to run the search box. This is the most authentic feeling of using others' code: it can even allow a third party to store the code used by your application. This is important because Google is responsible for maintenance and you will be able to automatically benefit from Google's upgrades to JavaScript files. Google will not change the API without notice, so your code can still work even if the Javascript file is changed.

Gsearchcontrol object

Another concealed operation is the gsearchcontrol object created in the onload () JavaScript function. To create this object, you only need to call the code in listing 8.

Listing 8. Create a gsearchcontrol object

// Create the Google search control
VaR searchcontrol = new gsearchcontrol ();

The required HTML code is very simple: you only need to use a div tag and an ID that javascript can reference, as shown in listing 9.

Listing 9. HTML code used to create a search control

<Div id = "searchcontrol"/>

What does Google's JavaScript look like?

Google's JavaScript is not easy to understand. First, the UDS. js Javascript file finds some local settings, handles some Google-specific tasks, verifies your Google key, and then loads two other scripts: http://www.google.com/uds/js/locale/en/uistrings.js and http://www.google.com/uds/js/uds_compiled.js. If you are interested, you can find out and carefully understand these two files, but note: it is very difficult to fully understand Advanced Code, and its format is daunting! For most people, they only need to know how to use these files without understanding the meaning of each row.

Similarly, Google's code handles various things behind the scenes. It creates a new text box, some images as icons, and a button for calling a JavaScript function. Therefore, you get all behaviors for free. Although you should understand the basic working principles, it is more convenient to use the Code directly and then write the remaining parts of the application.

Ajax is not just your own code

Ajax applications not only use XMLHttpRequest; they can be said to be a way to develop Web applications asynchronously. Even if you have not compiled any Ajax-specific code, you have created an Ajax application. Thanks to Google: It does most of the work, and you enjoy it!

In-depth exploration of Google's Ajax search API

So far, you should complete these steps and apply them to your own applications. The simplest application is to drag a div into the web page and add the Javascript shown in Listing 1 to the web page. Then you can use Google to search.

However, there are more interesting things than that. It is not limited to this set of specific options or controls. You can post web results, blog results, and video results. If appropriate, You can integrate each result into a web application. For example, you can provide multiple search controls, each of which is used to search for a type of results. You can also include the Google search control in a span element and place it in the middle of the content of other applications, rather than in a div on the side. In any case, you should be sure that Google search is built for your needs, rather than modifying your own applications to adapt to Google.

Conclusion

Based on the knowledge of this literature, it is not difficult to apply the Google search box and other Google APIs to your own Ajax applications. However, more importantly, you should understand how to use public APIs. For example, Amazon.com also provides a public API that allows you to perform the same web search for books and other amazon products. You can find your favorite public APIs to go beyond the limits of your programming skills. In fact, it is easy to create a site that integrates Google, Amazon.com, and Flickr.

Although it is important to figure out how to use Google (because Google provides good search algorithms and massive data storage), it is more important to learn how to use any public API. We should also begin to change our mindset and never regard our applications as the sum of Self-programming skills. On the contrary, it can be a door to various types of data. The data may be stored on servers of Google, Amazon.com, Del. icio. us, or anywhere else. Based on the data, you can add your own business or project content to get a very powerful and robust solution, which is far more than your own work.

Therefore, let us look farther and build big applications. Use data from a variety of places, not limited to your own code. Enjoy the fun of using others' code. In the subsequent articles in this series, I will talk about more technical issues, such as data formats.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.