Home About us Development Training Hints and Tips This page in plain text |
JavaScript Site SearchThere is not enough room here to show all the code of the search routine so the description below is just the bare outline of the routine. ArraysThe search works by scanning through an array of keywords in a JavaScript file. There are in fact five parallel arrays defined as follows:
// Number of matches found on this page
aHits = new Array(); // The keywords for each page aKeyWord = new Array(); // The URL of each page aURL = new Array(); // Page array sorted by number of hits aSorted = new Array(); // Description of each page aTitle = new Array(); The FoxPro code which builds the site parses each HTML document and pulls words from the Keyword and Description attributes to populate the arrays. These are the array members for the current page:
aURL[87]='foxsearch.htm';
aTitle[87]='Search page for Alvechurch Data web site'; aKeyWord[87]='alvechurch, data, search, find, javascript'; aHits[87]=0; Although the aTitle and aKeyword arrays are similar for many pages, they have to be kept separate because the string comparison is case-sensitive in JavaScript. The algorithm searches aKeyword but displays the equivalent entry from aTitle. Searching the Arrays
// Get the search target in lower case
lcTarget = document.searchForm.searchFor.value.toLowerCase() // Zero the hit counter and empty the array of hits lnFound = 0 for (thisPage=1; thisPage < aKeyWord.length; thisPage++) { aHits[thisPage] = 0 } // Break the target into an array of individual words // then scan through the keyword array once for each // of these words looking for a match. laWords=lcTarget.split(" ") for (lnWord = 0; lnWord < laWords.length; lnWord++) { for (thisPage=1; thisPage < aKeyWord.length; thisPage++) { if(laWords[lnWord] == "") { // Do nothing - this is a rogue thrown up by split } else { if (aKeyWord[thisPage].indexOf(laWords[lnWord]) > -1) { aHits[thisPage]++; if(aHits[thisPage]==1) { // First word found on the page so record a hit lnFound++; } } } } } // Write the array in the centre of this page if (lnFound==0) { writeResult(loPlaceHolder, "No pages include '" + lcTarget + "'"); } else { // We've found some pages writeResult(loPlaceHolder, lnFound + " pages found."); showResults(loPlaceHolder, lnFound, lcTarget) lnFound=0; } } return false The functions writeResult() and showResults() use the Document Object Model to put the results of the search into the centre of the page. |