One of the major advantages of an Ajax style search box is that users can perform their queries and get their results without leaving the page. However, some webmasters prefer that their users go to a separate results page after they enter a search. The Ajax search library supports this "two-page" use case as well, and since this is a question that we see from time to time we've set up a simple demo site.
To create this page we wrote a simple form in HTML and added JavaScript to add the "Google Custom Search" branding in the search box. View source to see all the details.
When the user submits the form, they are taken to a results page which has the following HTML structure:
<div id="results">Loading...</div>
We then tell the search library to draw its search box and results in the div we just created:
// Draw the control in content div
customSearchControl.draw('results');
Since the user came to this page from our search form, their query terms are now part of the page URL, so all we need to do now is extract them and execute their query:
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].substr(0, 1) == 'q') {
return unescape(parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
// See the source code of the results page for full details.
...
// Run a query
customSearchControl.execute(getQuery());
There is one more optional setting that you might be interested in. The second page which we've just created contains a search box that will allow the user to perform searches on this same page. If you would prefer for the search box not to appear on this results page we can add the following HTML to the page:
<input style="display:none" id="hidden-input" />
We hide the input box because we don't want the Ajax search library to render the usual query input box, just to show the results. We then tell the search library to draw its search box in the hidden input, making it invisible:
// Set drawing options to use our hidden input box.
var drawOptions = new google.search.DrawOptions();
drawOptions.setInput(document.getElementById('hidden-input'));
// Change the draw call to include our new options.
customSearchControl.draw('results', drawOptions);
To see an example of a two-page search setup with a hidden query input, visit this page.
To learn more about the Google Custom Search API, read our documentation. If you run into any problems while setting this up, post your question in our discussion group or hop on our IRC channel.
Hiç yorum yok:
Yorum Gönder